Rob Chartier ~ Contemplation...

.NET, C#, Work, etc.

News






www.flickr.com
This is a Flickr badge showing public photos from Rob & Kat Chartier. Make your own badge here.


Even Quicker Links

Quick Tip: C# File Info

This is nothing new, but I felt the need to share since so many miss it.

Many times I see stuff like this being done:

string FolderPath = FilePath.Substring(0, FilePath.LastIndexOf(@"\"));

Obviously they are trying to get the full path to a file.  Next time your thinking about doing something like that consider:

System.IO.FileInfo fi = new System.IO.FileInfo(FilePath);

string FolderPath = fi.DirectoryName;

Much nicer.

While I'm on the topic take a look at all the other goodies in the System.IO.FileInfo class:

fi.Extension

fi.FullName

fi.Name

fi.Length

fi.Directory.FullName

fi.Directory.Name

fi.Directory.Root.FullName

fi.DirectoryName

Not to mention these methods:

fi.Open();

fi.OpenRead();

fi.OpenText();

fi.OpenWrite();

More:  http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemIOFileInfoClassTopic.asp

 

Comments

Scott Weinstein said:

yes, the FileInfo class is very nice, but if you simply want the directory name you're probably better off using Path.GetDirectoryName()
# August 31, 2004 3:30 PM

Adam said:

Also not to mention that the FileInfo class demands FileIOAccess.Read permission and you may or may not have those rights whereas the Path class does not.
# August 31, 2004 3:53 PM

Paddy said:

Hey Buddy,

Thanks a bunch.

I am new to C# and these kindda quick tips are really handy :-)

Thanks again,

Paddy.

# April 24, 2007 5:44 PM

wntr brussel said:

Great tip, I'm also still guilty of going overboard  when trying to build a path/filename/extension etc.

# January 4, 2010 8:13 AM

Guest said:

I have imported a file into my c# application, when overwriting,a message box is displayed.I need the path of the file which I have already imported in my database.The message displayed should be like this:

Do you want to replace the existing file

          "here should be its path"

with the new file

          f:\data\abc.text

# April 28, 2010 2:59 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)