共用方式為


HOW TO:取得有關檔案、資料夾和磁碟機的資訊 (C# 程式設計手冊)

在 .NET Framework 中,您可以使用下列類別 (Class) 存取檔案系統資訊:

FileInfoDirectoryInfo 類別表示檔案或目錄,而包含的屬性 (Property) 可公開 NTFS 檔案系統支援的許多檔案屬性 (Attribute)。 這兩個類別也包含可用來開啟、關閉、移動和刪除檔案及資料夾的方法。 只要將表示檔案、資料夾或磁碟機的名稱傳遞給建構函式 (Constructor),就可以建立這些類別的執行個體 (Instance)。

System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\");

您還可以呼叫 DirectoryInfo.GetDirectoriesDirectoryInfo.GetFilesDriveInfo.RootDirectory,取得檔案、資料夾或磁碟機的名稱。

System.IO.DirectorySystem.IO.File 類別提供的靜態 (Static) 方法可用來擷取目錄及檔案的相關資訊。

範例

在下列範例中,會示範各種方法來存取檔案和資料夾的相關資訊。

class FileSysInfo
{
    static void Main()
    {
        // You can also use System.Environment.GetLogicalDrives to
        // obtain names of all logical drives on the computer.
        System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\");
        Console.WriteLine(di.TotalFreeSpace);
        Console.WriteLine(di.VolumeLabel);

        // Get the root directory and print out some information about it.
        System.IO.DirectoryInfo dirInfo = di.RootDirectory;
        Console.WriteLine(dirInfo.Attributes.ToString());

        // Get the files in the directory and print out some information about them.
        System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");


        foreach (System.IO.FileInfo fi in fileNames)
        {
            Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
        }

        // Get the subdirectories directly that is under the root.
        // See "How to: Iterate Through a Directory Tree" for an example of how to
        // iterate through an entire tree.
        System.IO.DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*");

        foreach (System.IO.DirectoryInfo d in dirInfos)
        {
            Console.WriteLine(d.Name);
        }

        // The Directory and File classes provide several static methods
        // for accessing files and directories.

        // Get the current application directory.
        string currentDirName = System.IO.Directory.GetCurrentDirectory();
        Console.WriteLine(currentDirName);           

        // Get an array of file names as strings rather than FileInfo objects.
        // Use this method when storage space is an issue, and when you might
        // hold on to the file name reference for a while before you try to access
        // the file.
        string[] files = System.IO.Directory.GetFiles(currentDirName, "*.txt");

        foreach (string s in files)
        {
            // Create the FileInfo object only when needed to ensure
            // the information is as current as possible.
            System.IO.FileInfo fi = null;
            try
            {
                 fi = new System.IO.FileInfo(s);
            }
            catch (System.IO.FileNotFoundException e)
            {
                // To inform the user and continue is
                // sufficient for this demonstration.
                // Your application may require different behavior.
                Console.WriteLine(e.Message);
                continue;
            }
            Console.WriteLine("{0} : {1}",fi.Name, fi.Directory);
        }

        // Change the directory. In this case, first check to see
        // whether it already exists, and create it if it does not.
        // If this is not appropriate for your application, you can
        // handle the System.IO.IOException that will be raised if the
        // directory cannot be found.
        if (!System.IO.Directory.Exists(@"C:\Users\Public\TestFolder\"))
        {
            System.IO.Directory.CreateDirectory(@"C:\Users\Public\TestFolder\");
        }

        System.IO.Directory.SetCurrentDirectory(@"C:\Users\Public\TestFolder\");

        currentDirName = System.IO.Directory.GetCurrentDirectory();
        Console.WriteLine(currentDirName);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

穩固程式設計

處理使用者指定的路徑字串時,也必須處理下列情形的例外狀況 (Exception):

  • 檔案名稱格式不正確, 例如包含無效字元或只有泛空白字元 (White Space)。

  • 檔案名稱為 null。

  • 檔案名稱長度超過系統定義的最大長度。

  • 檔案名稱包含冒號 (:)。

如果應用程式沒有足夠的權限可以讀取指定的檔案,則無論路徑是否存在,Exists 方法都會傳回 false,此方法並不會擲回例外狀況。

請參閱

參考

System.IO

概念

C# 程式設計手冊

其他資源

檔案系統和登錄 (C# 程式設計手冊)