public sealed class Path
|
A path can contain absolute or relative location information. Absolute paths fully specify a location: the file or directory can be uniquely identified regardless of the current location. Relative paths specify a partial location: the current location is used as the starting point when locating a file specified with a relative path. To determine the current directory, call Directory.GetCurrentDirectory.
Most members of the Path class do not interact with the file system and do not verify the existence of the file specified by a path string.Path class members that modify a path string, such as Path.ChangeExtension, have no effect on names of files in the file system.Path members do, however, validate the contents of a specified path string, and throw an ArgumentException if the string contains characters that are not valid in path strings, as defined in Path.InvalidPathChars. For example, on Windows-based desktop platforms, invalid path characters might include quote ("), less than (<), greater than (>), pipe (|), backspace (\b), null (\0), and Unicode characters 16 through 18 and 20 through 25.
The members of the Path class enable you to quickly and easily perform common operations such as determining whether a file name extension is part of a path, and combining two strings into one path name.
All members of the Path class are static and can therefore be called without having an instance of a path.
In members that accept a path, the path can refer to a file or just a directory. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, all of the following are acceptable paths:
Because all these operations are performed on strings, it is impossible to verify that the results are valid in all scenarios. For example, the Path.GetExtension method parses a string that you pass to it and returns the extension from that string. However, this does not mean that a file with that extension exists on the disk.
AltDirectorySeparatorChar | Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization. |
DirectorySeparatorChar | Provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organization. |
InvalidPathChars | Provides a platform-specific array of characters that cannot be specified in path string arguments passed to members of the Path class. |
PathSeparator | A platform-specific separator character used to separate path strings in environment variables. |
VolumeSeparatorChar | Provides a platform-specific volume separator character. |
ChangeExtension | Changes the extension of a path string. |
Combine | Combines two path strings. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetDirectoryName | Returns the directory information for the specified path string. |
GetExtension | Returns the extension of the specified path string. |
GetFileName | Returns the file name and extension of the specified path string. |
GetFileNameWithoutExtension | Returns the file name of the specified path string without the extension. |
GetFullPath | Returns the absolute path for the specified path string. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetPathRoot | Gets the root directory information of the specified path. |
GetTempFileName | Returns a unique temporary file name and creates a zero-byte file by that name on disk. |
GetTempPath | Returns the path of the current system's temporary folder. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
HasExtension | Determines whether a path includes a file name extension. |
IsPathRooted | Gets a value indicating whether the specified path string contains absolute or relative path information. |
ToString (inherited from System.Object) |
See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public static readonly char AltDirectorySeparatorChar;
|
The value of this field is a backslash ('\') on Unix, and a slash ('/') on Windows and Macintosh operating systems.
Console.WriteLine("Path.AltDirectorySeparatorChar={0}", Path.AltDirectorySeparatorChar); Console.WriteLine("Path.DirectorySeparatorChar={0}", Path.DirectorySeparatorChar); Console.WriteLine("Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine("Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar); Console.Write("Path.InvalidPathChars="); foreach (char c in Path.InvalidPathChars) Console.Write(c); Console.WriteLine();
public static readonly char DirectorySeparatorChar;
|
The value of this field is a backslash ('\') on Unix, and a slash ('/') on Windows and Macintosh operating systems.
Console.WriteLine("Path.AltDirectorySeparatorChar={0}", Path.AltDirectorySeparatorChar); Console.WriteLine("Path.DirectorySeparatorChar={0}", Path.DirectorySeparatorChar); Console.WriteLine("Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine("Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar); Console.Write("Path.InvalidPathChars="); foreach (char c in Path.InvalidPathChars) Console.Write(c); Console.WriteLine();
public static readonly char[] InvalidPathChars;
|
Console.WriteLine("Path.AltDirectorySeparatorChar={0}", Path.AltDirectorySeparatorChar); Console.WriteLine("Path.DirectorySeparatorChar={0}", Path.DirectorySeparatorChar); Console.WriteLine("Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine("Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar); Console.Write("Path.InvalidPathChars="); foreach (char c in Path.InvalidPathChars) Console.Write(c); Console.WriteLine();
public static readonly char PathSeparator;
|
Console.WriteLine("Path.AltDirectorySeparatorChar={0}", Path.AltDirectorySeparatorChar); Console.WriteLine("Path.DirectorySeparatorChar={0}", Path.DirectorySeparatorChar); Console.WriteLine("Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine("Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar); Console.Write("Path.InvalidPathChars="); foreach (char c in Path.InvalidPathChars) Console.Write(c); Console.WriteLine();
public static readonly char VolumeSeparatorChar;
|
Console.WriteLine("Path.AltDirectorySeparatorChar={0}", Path.AltDirectorySeparatorChar); Console.WriteLine("Path.DirectorySeparatorChar={0}", Path.DirectorySeparatorChar); Console.WriteLine("Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine("Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar); Console.Write("Path.InvalidPathChars="); foreach (char c in Path.InvalidPathChars) Console.Write(c); Console.WriteLine();
path
extension
On Windows-based desktop platforms, if path is null or an empty string (""), the path information is returned unmodified. If extension is null, the returned string contains the specified path with its extension removed. If path has no extension, and extension is not null, the returned path string contains extension appended to the end of path.
Exception Type | Condition |
---|---|
ArgumentException | The path contains one or more of the invalid characters defined in Path.InvalidPathChars. |
The extension parameter can contain multiple periods and any valid path characters, and can be any length. If extension is null, the returned string contains the contents of path with the last period and all characters following it removed.
If extension is an empty string, the returned path string contains the contents of path with any characters following the last period removed.
If path does not have an extension and extension is not null, the returned string contains path followed by extension.
If extension is not null and does not contain a leading period, the period is added.
If path contains a multiple extension separated by multiple periods, the returned string contains the contents of path with the last period and all characters following it replaced by extension. For example, if path is "\Dir1\examples\pathtests.csx.txt" and extension is "cs", the modified path is "\Dir1\examples\pathtests.csx.cs".
It is not possible to verify that the returned results are valid in all scenarios. For example, if path is empty, extension is appended.
string goodFileName = @"C:\mydir\myfile.com.extension"; string badFileName = @"C:\mydir\"; string result; result = Path.ChangeExtension(goodFileName, ".old"); Console.WriteLine("ChangeExtension({0}, '.old') returns '{1}'", goodFileName, result); result = Path.ChangeExtension(goodFileName, ""); Console.WriteLine("ChangeExtension({0}, '') returns '{1}'", goodFileName, result); result = Path.ChangeExtension(badFileName, ".old"); Console.WriteLine("ChangeExtension({0}, '.old') returns '{1}'", badFileName, result);
path1
path2
Exception Type | Condition |
---|---|
ArgumentException | IsPathRooted is true. -or- path1 is not empty, and path2 is a volume letter, a UNC share name, or begins with a path separator character. -or- path1 or path2 contain one or more of the invalid characters defined in Path.InvalidPathChars. |
ArgumentNullException | path1 or path2 is null. |
If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, the root is returned.
If path2 has no leading white space and begins with a Universal Naming Convention (UNC) name or volume letter, this will not throw an exception. Because the parameters are not parsed if they have white space, if path2 is " c:\\ ", this will be appended successfully and will not be verified. Strings such as "c :\\" and " \\ hello.txt" will also be accepted.
Not all invalid characters for directory and file names are interpreted as unacceptable by the Combine method, because you can use these characters for search wildcard characters. For example, while
Path.Combine("c:\\", "*.txt")
might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the Combine method.
using System; using System.IO; public class ChangeExtensionTest { public static void Main() { string path1 = "c:\\temp"; string path2 = "subdir\\file.txt"; string path3 = "c:\\temp.txt"; string path4 = "c:^*&)(_=@#'\\^.*(.txt"; string path5 = ""; string path6 = null; CombinePaths(path1, path2); CombinePaths(path1, path3); CombinePaths(path3, path2); CombinePaths(path4, path2); CombinePaths(path5, path2); CombinePaths(path6, path2); } private static void CombinePaths(string p1, string p2) { try { string combination = Path.Combine(p1, p2); Console.WriteLine("When you combine '{0}' and '{1}', the result is: {2}'{3}'", p1, p2, Environment.NewLine, combination); } catch (Exception e) { Console.WriteLine("You cannot combine '{0}' and '{1}' because: {2}{3}", p1, p2, Environment.NewLine, e.Message); } Console.WriteLine(); } }
~Path(); |
path
Exception Type | Condition |
---|---|
ArgumentException | path contains invalid characters, is empty, or contains only white spaces. |
string fileName = @"C:\mydir\myfile.ext"; string path = @"C:\mydir\"; string rootPath = @"C:\"; string directoryName; directoryName = Path.GetDirectoryName(fileName); Console.WriteLine("GetDirectoryName('{0}') returns '{1}'", fileName, directoryName); directoryName = Path.GetDirectoryName(path); Console.WriteLine("GetDirectoryName('{0}') returns '{1}'", path, directoryName); directoryName = Path.GetDirectoryName(rootPath); Console.WriteLine("GetDirectoryName('{0}') returns '{1}'", rootPath, directoryName);
path
Exception Type | Condition |
---|---|
ArgumentException | path contains one or more of the invalid characters defined in Path.InvalidPathChars. |
string fileName = @"C:\mydir.old\myfile.ext"; string path = @"C:\mydir.old\"; string extension; extension = Path.GetExtension(fileName); Console.WriteLine("GetExtension('{0}') returns '{1}'", fileName, extension); extension = Path.GetExtension(path); Console.WriteLine("GetExtension('{0}') returns '{1}'", path, extension);
path
Exception Type | Condition |
---|---|
ArgumentException | path contains one or more of the invalid characters defined in Path.InvalidPathChars. |
The separator characters used to determine the start of the file name are Path.DirectorySeparatorChar and Path.AltDirectorySeparatorChar.
string fileName = @"C:\mydir\myfile.ext"; string path = @"C:\mydir\"; string result; result = Path.GetFileName(fileName); Console.WriteLine("GetFileName('{0}') returns '{1}'", fileName, result); result = Path.GetFileName(path); Console.WriteLine("GetFileName('{0}') returns '{1}'", path, result);
path
Exception Type | Condition |
---|---|
ArgumentException | path contains one or more of the invalid characters defined in Path.InvalidPathChars. |
string fileName = @"C:\mydir\myfile.ext"; string path = @"C:\mydir\"; string result; result = Path.GetFileNameWithoutExtension(fileName); Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", fileName, result); result = Path.GetFileName(path); Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", path, result);
path
Exception Type | Condition |
---|---|
ArgumentException | path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by Path.InvalidPathChars. -or- The system could not retrieve the absolute path. |
SecurityException | The caller does not have the required permissions. |
ArgumentNullException | path is null. |
PathTooLongException | The length of path or the absolute path information for path exceeds the system-defined maximum length. |
The file or directory specified by path is not required to exist. For example, if c:\temp\newdir is the current directory, calling GetFullPath on a file name such as test.txt returns c:\temp\newdir\test.txt. The file need not exist.
However, if path does exist, the caller must have permission to obtain path information for path. Note that unlike most members of the Path class, this method accesses the file system.
This method uses current directory and current volume information to fully qualify path. If you only specify a file name in path, GetFullPath returns the fully qualified path of the current directory.
If you pass in a short file name, it is not expanded to a long file name.
string fileName = "myfile.ext"; string path = @"\mydir\"; string fullPath; fullPath = Path.GetFullPath(path); Console.WriteLine("GetFullPath('{0}') returns '{1}'", path, fullPath); fullPath = Path.GetFullPath(fileName); Console.WriteLine("GetFullPath('{0}') returns '{1}'", fileName, fullPath);
public virtual int GetHashCode(); |
path
Exception Type | Condition |
---|---|
ArgumentException | path contains one or more of the invalid characters defined in Path.InvalidPathChars, -or- String.Empty was passed to path. |
Possible patterns for the string returned by this method are as follows:
string path = @"\mydir\"; string fileName = "myfile.ext"; string fullPath = @"C:\mydir\myfile.ext"; string pathRoot; pathRoot = Path.GetPathRoot(path); Console.WriteLine("GetPathRoot('{0}') returns '{1}'", path, pathRoot); pathRoot = Path.GetPathRoot(fileName); Console.WriteLine("GetPathRoot('{0}') returns '{1}'", fileName, pathRoot); pathRoot = Path.GetPathRoot(fullPath); Console.WriteLine("GetPathRoot('{0}') returns '{1}'", fullPath, pathRoot);
public static string GetTempFileName(); |
string fileName = Path.GetTempFileName(); FileInfo fileInfo = new FileInfo(fileName); Console.WriteLine("File '{0}' created of size {1} bytes", fileName, fileInfo.Length); // Write some text to the file. FileStream f = new FileStream(fileName, FileMode.Open); StreamWriter s = new StreamWriter(f); s.WriteLine("Output to the file"); s.Close(); f.Close(); fileInfo.Refresh(); Console.WriteLine("File '{0}' now has size {1} bytes", fileName, fileInfo.Length);
public static string GetTempPath(); |
Exception Type | Condition |
---|---|
SecurityException | The caller does not have the required permissions. |
string tempPath = Path.GetTempPath(); Console.WriteLine("Temporary path is '{0}'", tempPath); DirectoryInfo tempDir = new DirectoryInfo(tempPath); Console.WriteLine("{0} contains {1} files", tempPath, tempDir.GetFiles().Length);
public Type GetType(); |
path
Exception Type | Condition |
---|---|
ArgumentException | path contains one or more of the invalid characters defined in Path.InvalidPathChars. |
string fileName1 = "myfile.ext"; string fileName2 = @"mydir\myfile"; string path = @"C:\mydir.ext\"; bool result; result = Path.HasExtension(fileName1); Console.WriteLine("HasExtension('{0}') returns {1}", fileName1, result); result = Path.HasExtension(fileName2); Console.WriteLine("HasExtension('{0}') returns {1}", fileName2, result); result = Path.HasExtension(path); Console.WriteLine("HasExtension('{0}') returns {1}", path, result);
path
Exception Type | Condition |
---|---|
ArgumentException | path contains one or more of the invalid characters defined in Path.InvalidPathChars. |
IsPathRooted returns true for path strings such as "\\MyDir\\MyFile.txt" and "C:\\MyDir". It returns false for path strings such as "MyDir".
string fileName = @"C:\mydir\myfile.ext"; string UncPath = @"\\myPc\mydir\myfile"; string relativePath = @"mydir\sudir\"; bool result; result = Path.IsPathRooted(fileName); Console.WriteLine("IsPathRooted('{0}') returns {1}", fileName, result); result = Path.IsPathRooted(UncPath); Console.WriteLine("IsPathRooted('{0}') returns {1}", UncPath, result); result = Path.IsPathRooted(relativePath); Console.WriteLine("IsPathRooted('{0}') returns {1}", relativePath, result);
protected object MemberwiseClone(); |
public virtual string ToString(); |