共用方式為


HOW TO:建立檔案或資料夾 (C# 程式設計手冊)

這個範例會在電腦上建立資料夾和子資料夾,然後在子資料夾中建立新的檔案,並在檔案中寫入一些資料。

範例

public class CreateFileOrFolder
{
    static void Main()
    {
        // Specify a "currently active folder"
        string activeDir = @"c:\testdir2";

        //Create a new subfolder under the current active folder
        string newPath = System.IO.Path.Combine(activeDir, "mySubDir");

        // Create the subfolder
        System.IO.Directory.CreateDirectory(newPath);

        // Create a new file name. This example generates
        // a random string.
        string newFileName = System.IO.Path.GetRandomFileName();

        // Combine the new file name with the path
        newPath = System.IO.Path.Combine(newPath, newFileName);

        // Create the file and write to it.
        // DANGER: System.IO.File.Create will overwrite the file
        // if it already exists. This can occur even with
        // random file names.
        if (!System.IO.File.Exists(newPath))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(newPath))
            {
                for (byte i = 0; i < 100; i++)
                {
                    fs.WriteByte(i);
                }
            }
        }

        // Read data back from the file to prove
        // that the previous code worked.
        try
        {
            byte[] readBuffer = System.IO.File.ReadAllBytes(newPath);
            foreach (byte b in readBuffer)
            {
                Console.WriteLine(b);
            }
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

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

如果資料夾已存在,CreateDirectory 不會執行任何動作,也不會擲回例外狀況。 不過,File.Create 會覆寫任何現有的檔案。 若要避免覆寫現有檔案,您可以使用 OpenWrite 方法,並指定可附加檔案 (而不是覆寫檔案) 的 FileMode.OpenOrCreate 選項。

以下條件可能會造成例外狀況:

安全性

在部分信任的情況下可能會擲回 SecurityException 類別的執行個體。

如果使用者不具有建立資料夾的權限,這個範例將會擲回 UnauthorizedAccessException 類別的執行個體。

請參閱

參考

System.IO

概念

C# 程式設計手冊

其他資源

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