C#和VB2005初学者如何使用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值