December 2007
Intermediate to advanced
896 pages
19h 57m
English
You need to separate the constituent parts of a path and place them into separate variables.
Use the static methods of the Path class:
public static void ParsePath(string path)
{
string root = Path.GetPathRoot(path);
string dirName = Path.Get DirectoryName(path);
string fullFileName = Path.GetFileName(path);
string fileExt = Path.GetExtension(path);
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(path);
StringBuilder format = new StringBuilder();
format.Append("ParsePath of {0} breaks up into the following pieces:" +
Environment.NewLine + "\tRoot: {1}" +
Environment.NewLine + "\t");
format.Append("Directory Name: {2}" +
Environment.NewLine + "\tFull File Name: {3}" +
Environment.NewLine + "\t");
format.Append("File Extension: {4}" +
Environment.NewLine + "\tFile Name Without Extension: {5}" +
Environment.NewLine + "");
Console.WriteLine(format.ToString(),path,root,dirName,
fullFileName,fileExt,fileNameWithoutExt);
}If the string C:\test\tempfile.txt is passed to this method, the output looks like this:
ParsePath of C:\test\tempfile.txt breaks up into the following pieces: Root: C:\ Directory Name: C:\test Full File Name: tempfile.txt File Extension: .txt File Name Without Extension: tempfile
The Path class contains methods that can be used to parse a given path. Using these classes is much easier and less error-prone than writing path-and filename-parsing code. If these classes are not used, you could also introduce security ...
Read now
Unlock full access