Wednesday, January 18, 2006

Say screw it to parsing filenames

I recently discovered some builtin classes to parse file paths instead of awkward .IndexOf / substring combinations

dim filename as string = "c:\windows\temp\stuff\myfile.txt"

the IO.Path has many shared methods that allow parsing and manipulation

IO.Path.ChangeExtension(filename, "xml") 'c:\windows\temp\stuff\myFile.xml
IO.Path.Combine() 'have not played with this one yet
IO.Path.GetDirectoryName(filename) 'c:\windows\temp\stuff
IO.Path.GetExtension(filename) '.txt
IO.Path.GetFileName(filename) 'myfile.txt
IO.Path.GetFileNameWithoutExtension(filename) 'myfile
IO.Path.GetFullPath(filename) 'c:\windows\temp\stuff\myfile.txt
IO.Path.GetFullPath("blah.txt") 'c:\vss\project\bin\blah.txt"
IO.Path.GetPathRoot(filename) 'c:IO.Path.GetTempFileName() 'c:\temp\tmp260A.tmp (gauranteed unique file)
IO.Path.GetTempPath() 'c:\temp\ (gets windows temp dir)
IO.Path.HasExtension(filename) 'True (false if no file extension)
IO.Path.IsPathRooted(filename) 'True (path is an absolute or relative. absolute in this case)

I recently used this for a project where I wanted to create the directory for a file if the directory did not exist.


Note that CreateDirectory will recursively create any missing directories (when I ran this I only had a "c:\temp" directory).

Another handy method is IO.Directory.GetCurrentDirectory() which gets the current working directory of the application


Post a Comment

<< Home