Article Options
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.20289855072465 out of 5
 69 people have rated this page
Article Score100629
Sponsored Links