Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Framework  »  FileSystemInfo Class in C# and VB.NET for beginners
FileSystemInfo Class in C# and VB.NET for beginners
by Ashish Jaiman | Published  02/18/2002 | .NET Framework | Rating:
Ashish Jaiman

Ashish works as a Sr. Software Developer with Lexign Inc., an end-to-end trusted electronic transaction management software provider (http://www.lexign.com).

Ashish has 6 years of experience in designing and developing distributed systems, server technologies and web based software applications using Microsoft technologies, Java, XML and .NET. He holds MCSD (Microsoft Certified Software Developer) and SCJP (Sun Certified Java Programmer) certifications.

Contact Ashish at jaimanalwar@yahoo.com or ashish.jaiman@lexign.com.

 

View all articles by Ashish Jaiman...
FileSystemInfo Class in C# and VB.NET for beginners

FileSystemInfo Class

One of the rich experiences in working with .NET is a huge collection of Base Class Libraries. The .NET Framework class library is a library of classes, interfaces, and value types that are included in the Microsoft .NET Framework SDK. This library provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.

System.IO namespace contains types that allow synchronous and asynchronous reading and writing on data streams and files.

To parse information of lots of files and directories, the FileSystemInfo class comes in handy. It is an abstract class and contains members (methods, properties …) that are common to file and directory manipulation. A FileSystemInfo object can represent either a file or a directory. The implementation of this abstract class is done in FileInfo and DirectoryInfo class. The Members would take full path (absolute or relative) or UNC path if they require path as one of the parameters.

In VB6 you could have used the Scripting Library (FileSystemObject) to manipulate the Files and directories.

Listing1: Members of FileSystemInfo class (for more information refer to MSDN)

namedescription
AttributesGets or sets the FileAttributes of the current FileSystemInfo.
CreationTimeGets or sets the creation time of the current FileSystemInfo object
ExistsGets a value indicating whether the file or directory exists
ExtensionGets the string representing the extension part of the file.
FullNameGets the full path of the directory or file.
LastAccessTimeGets or sets the time the current file or directory was last accessed
LastWriteTimeGets or sets the time when the current file or directory was last written to.
NameFor files, gets the name of the file. For directories, gets the name of the last directory in the hierarchy if a hierarchy exists. Otherwise, the Name property gets the name of the directory
DeleteDeletes a file or directory.
FullPathRepresents the fully qualified path of the directory or file.
OriginalPathThe path originally specified by the user, whether relative or absolute.

The FileInfo class and DirectoryInfo class extends FileSystemInfo class and each add some more members to themselves for specific operations.

FileInfo Class

The FileInfo class provides instance methods for the creation, copying, deletion, moving, and opening of files, and provides members to create FileStream objects.

Listing2: List of some members of FileInfo class (for more information refer to MSDN). I have excluded the members of FileSystemInfo class overridden by FileInfo class and implemented by FileSystemInfo class.

namedescription
DirectoryGets an instance of the parent directory.
DirectoryNameGets a string representing the directory's full path.
LengthGets the size of the current file or directory.
NameGets the name of the file.
CreateCreates a file.
CreateTextCreates a StreamWriter that writes a new text file.
OpenOpens a file with various read/write and sharing privileges
OpenReadCreates a read-only FileStream.
OpenTextCreates a StreamReader with UTF8 encoding that reads from an existing text file.
OpenWriteCreates a write-only FileStream
AppendTextCreates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
CopyToCopies an existing file to a new file.
MoveToRenames/moves an existing file.

DirectoryInfo Class

The DirectoryInfo class provides instance methods for creating, moving, and enumerating through directories and subdirectories.

Listing3: List of some members of DirectoryInfo class (for more information refer to MSDN), I have excluded the members of FileSystemInfo Class overridden by Directory class and implemented by FileSystemInfo class.

namedescription
ParentGets the parent directory of a specified subdirectory.
RootGets the root portion of a path.
CreateCreates a directory.
CreateSubDirectoryCreates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.
GetDirectoriesReturns the subdirectories of the current directory
GetFilesReturns a file list from the current directory.
GetFileSystemInfosRetrieves an array of strongly typed FileSystemInfo objects.
MoveToMoves a DirectoryInfo instance and its contents to a new path.

Below is an example of extending the FileSystemInfo class and adding IsDirectory and IsFile properties to it, new members can be added to roll a new custom class rather then using FileInfo or DirectoryInfo class. We can delegate most of the functionality to the FileInfo and DirectoryInfo classes in our custom class.

C# Implementation

using System;
using System.IO;

public class CFileSystem:FileSystemInfo
{
    FileInfo mobjFileInfo;
    DirectoryInfo mobjDirectoryInfo;
    bool mblnIsDirectory = true;

    public CFileSystem(string xstrFilePath)
    {
        try
        {
            mobjDirectoryInfo = new DirectoryInfo(xstrFilePath);
            if (!(mobjDirectoryInfo.Extension.Length==0))
            {
                mblnIsDirectory = false;
                mobjDirectoryInfo= null;
                mobjFileInfo = new FileInfo(xstrFilePath);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine( ex.ToString());
        }
    }

    public override void Delete()
    {
        if (mblnIsDirectory)
        {
            mobjDirectoryInfo.Delete();
        }
        else
        {
            mobjFileInfo.Delete();
        }
    }

    public override bool Exists
    {
        get
        {
            if (mblnIsDirectory)
            {
                return mobjDirectoryInfo.Exists;
            }
            else
            {
                return mobjFileInfo.Exists;
            }
        }
    }

    public string Fullname
    {
        get
        {
            if (mblnIsDirectory)
            {
                return mobjDirectoryInfo.FullName;
            }
            else
            {
                return mobjFileInfo.FullName;
            }
        }
    }

    public override string Name
     {
         get
         {
             if (mblnIsDirectory)
             {
                 return mobjDirectoryInfo.Name;
             }
             else
             {
                 return mobjFileInfo.Name;
             }
         }
     }

    public bool IsDirectory
    {
        get
        {
            return mblnIsDirectory;
        }
    }

    public bool IsFile
    {
        get
        {
            return !mblnIsDirectory;
        }
    }
}

VB.NET Implementation

Imports System.IO
 
Public Class CFileSystem
    Inherits System.IO.FileSystemInfo
 
    Private mobjFileInfo As FileInfo
    Private mobjDirectoryInfo As DirectoryInfo
    Private mblnIsDirectory As Boolean = True
 
    Public Sub New(ByVal xstrFilePath As String)
        Try
            mobjDirectoryInfo = New DirectoryInfo(xstrFilePath)
            If Not mobjDirectoryInfo.Extension().Length = 0 Then
                mblnIsDirectory = False
                mobjDirectoryInfo = Nothing
                mobjFileInfo = New FileInfo(xstrFilePath)
            End If
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
        End Try
    End Sub
 
    Public Overrides Sub Delete()
        If mblnIsDirectory Then
            mobjDirectoryInfo.Delete()
        Else
            mobjFileInfo.Delete()
        End If
    End Sub
 
    Public Overrides ReadOnly Property Exists() As Boolean
        Get
            If mblnIsDirectory Then
                Exists = mobjDirectoryInfo.Exists
            Else
                Exists = mobjFileInfo.Exists
            End If
        End Get
    End Property
 
    Public Overrides ReadOnly Property FullName() As String
        Get
            If mblnIsDirectory Then
                FullName = mobjDirectoryInfo.FullName
            Else
                FullName = mobjFileInfo.FullName
            End If
        End Get
    End Property
 
    Public Overrides ReadOnly Property Name() As String
        Get
            If mblnIsDirectory Then
                Name = mobjDirectoryInfo.Name
            Else
                Name = mobjFileInfo.Name
            End If
        End Get
    End Property
 
    Public ReadOnly Property IsDirectory() As Boolean
        Get
            IsDirectory = mblnIsDirectory
        End Get
    End Property
 
    Public ReadOnly Property IsFile() As Boolean
        Get
            IsFile = mblnIsDirectory = False
        End Get
    End Property
 
End Class
Generated using PrettyCode.Encoder
How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:3.41176470588235 out of 5
 34 people have rated this page
Article Score89678
Related Articles
Comments    Submit Comment

Comment #1  (Posted by Bob Cummings on 04/15/2002)

I have tried using this class in asp.net to ennumerate directories on another server without success, eg path ="\\server\share\directory". I have also been unsuccessful trying to read drives on the server that have been mapped, eg path = "s:\directory". I am asked for credentials even though I have allowed windows authentication in the web.config. When I enter the credentials they are not recognized.

Any ideas?

Bob Cummings
 
Comment #2  (Posted by David Bundren on 06/27/2002)

I have experienced this as well in the context of using the FileInfo class from a windows service in C#. Let's try and put the resolution in this thread when someone finds it.
 
Comment #3  (Posted by Bob on 08/06/2002)

Think I have a solution - use Server.MapPath.

filePath =Server.MapPath( PATH );
to get the physical location of the file first, then use filePath
with your FileInfo object.

- Bob
 
Comment #4  (Posted by Greg on 04/08/2003)

Is there any way to access specific attributes of a file? Specifically I am referring to attributes such as; Title, Author, Comments (all can be found by right-clicking a file and then clicking summary). Are these attributes accessible through C#? I have tried the FileVersionInfo class but it seems that is specific to an executable. I would appreciate any ideas. Thank you.
 
Comment #5  (Posted by Naresh Shah on 06/10/2003)

I have same problem to get directory information from remote server. However I am getting information from the local server.
 
Comment #6  (Posted by rp on 08/12/2004)

The test for IsDirectory would fail if the File is something like C:\\README.

So shouldn't you change your test from:

if (!(mobjDirectoryInfo.Extension.Length==0))
{
....
}

to something like:

if ((mobjDirectoryInfo.Attributes & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory)
{
...
}


 
Comment #7  (Posted by inderjeet on 11/02/2004)

what if directory name contains "." i:e "folder.name"then

System.IO.DirectoryInfo item = new System.IO.DirectoryInfo("Folder.Name");

item.extension would be ".Name" and IsDirectory would say its not directory....but it is.......
 
Comment #8  (Posted by an unknown user on 03/07/2005)
Rating
Thanks for the code!
Just want to save some time to reused code.
Cheers!
~Himadrish
 
Comment #9  (Posted by mansoor on 03/18/2005)
Rating
Thanks for sharing such nice information
 
Comment #10  (Posted by DenimChap on 04/04/2005)
Rating
From the description I presume that these classes are used for Windows applications only. Can you plz let me know if they can be used in a web application too?
 
Comment #11  (Posted by an unknown user on 09/07/2005)
Rating
use the TypeOf to test if a FileSystemInfo is a FileInfo or DirectoryInfo (if typeof myFSI is FileInfo then..) and CType to assign it to a strong type variable.
 
Comment #12  (Posted by Sandeep Dubey on 10/19/2005)
Rating
Any luck on Title, Author, Comments attributes of file through C#? Thank you.
 
Comment #13  (Posted by Kgari on 10/24/2005)
Rating
Hi, I am also experiencing a problem reading file from another server e.g (\\servername\dir\file.csv) , I mapped the drive to K: but I still get an error. And when I try Server.MapPath i get an error saying "A virtual path is expected" please help.

Kgari, from South Africa
 
Comment #14  (Posted by Peter on 10/26/2005)

If you run a mapped drive the machine must be logged on as the profile that has the drive mapped.

To get around this use full unc path conventions eg. "\\ServerName\FolderTree\Filename.extension"

Sometimes network configurations can block the accessing of data, this is to do with trust issues. To resolve these go into internet explorer and add the full unc path to the root folder you need to access and assign it full intranet trust. Once this is done open up a command prompt and type in "proxycfg -u" This specifys that all profiles on the machine should use the trust level settings you have just applied, look into it more though, I was talked through this issue by a networking guru, i'm just a lowly developer



 
Comment #15  (Posted by Mike Koch on 10/28/2005)
Rating
To check if we have a file or directory and have it work for directory names that have periods in them, you actually need to do this:

if ((System.IO.File.GetAttributes(xstrFilePath) & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory)

 
Comment #16  (Posted by an unknown user on 11/02/2005)
Rating
To implement the base class you wrap two objects that already implement that class and then write if statents all over the place. You are either an idiot or a genius. Guess which one I'm going with.
 
Comment #17  (Posted by an unknown user on 12/23/2005)
Rating
its a clear example for the beginners.
 
Comment #18  (Posted by Ebrahim Ahmed on 01/15/2006)
Rating
How i get the subdirectory's deleted if i dont know the names like the Temp file?
 
Comment #19  (Posted by an unknown user on 01/18/2006)
Rating
Because it provide the coplete information for what i searched.
Thank you and Good luck for future enhancements.

Thanks and Regards
Bharath.S

 
Comment #20  (Posted by an unknown user on 05/01/2006)
Rating
Gave me the exact info I was looking for: how to id if an item is a file or a directory. Thank you.
 
Comment #21  (Posted by an unknown user on 06/15/2006)
Rating
Lots of code. NO comments. It is clear that the author knows what he's talking about. Unfortunately, there isn't enough explanation in to code for beginners to follow his thoughts.
 
Comment #22  (Posted by an unknown user on 06/26/2006)
Rating
primitive wrapper
 
Comment #23  (Posted by an unknown user on 11/06/2006)
Rating
I am new to .net a object oriented programing... this article only tells me how to create the classes, but not how I should refference it or output it
 
Comment #24  (Posted by an unknown user on 12/26/2006)
Rating
Goood....
 
Comment #25  (Posted by an unknown user on 03/07/2007)
Rating
Very helpful article!!
 
Comment #26  (Posted by Vikas on 03/11/2007)
Rating
Is there any way to access specific attributes of a file? Specifically I am referring to attributes such as; Title, Author, Comments (all can be found by right-clicking a file and then clicking summary). Are these attributes accessible through C#?
 
Comment #27  (Posted by an unknown user on 07/19/2007)
Rating
How to use it in application. can you give example? thanks.
 
Comment #28  (Posted by an unknown user on 06/26/2008)
Rating
no supporting descriptions
 
Comment #29  (Posted by an unknown user on 12/01/2008)
Rating
mongetc
 
Comment #30  (Posted by toolsche on 02/24/2009)
Rating
To test if the file is a directory you could also use the following method:

public bool IsDir(string FilePath)
{
DirectoryInfo di = new DirectoryInfo(FilePath);
if (di.Exists) return true;
return false;
}


 
Comment #31  (Posted by an unknown user on 03/25/2009)
Rating
Nice, SAFE function to check if path is a file, not a directory, and if it exists.

Private Function IsPathAFileExist(ByVal sPath As String) As Boolean
Dim _dirInfo As DirectoryInfo = Nothing
Dim _fileInfo As FileInfo = Nothing
Dim _ret As Boolean = False
Try
_dirInfo = New DirectoryInfo(sPath)
If Not IsNothing(_dirInfo) AndAlso _dirInfo.Exists Then
If (_dirInfo.Attributes And FileAttributes.Directory) = FileAttributes.Directory Then
_ret = False
Else
_ret = True
End If
Else
_fileInfo = New FileInfo(sPath)
If Not IsNothing(_fileInfo) _
AndAlso (_fileInfo.Attributes And FileAttributes.Directory) <> FileAttributes.Directory _
AndAlso Path.HasExtension(sPath) _
AndAlso My.Computer.FileSystem.FileExists(sPath) Then
_ret = True
Else
_ret = False
End If
End If
Catch ex As Exception
_ret = False
Finally
IsPathAFileExist = _ret
End Try
End Function

 
Sponsored Links