如何:创建文件或文件夹
此示例在计算机上创建一个文件夹和一个子文件夹,然后在该子文件夹中创建一个新文件并将一些数据写入该文件。
示例
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 选项。
以下情况可能会导致异常:
文件夹名称格式不正确。例如,它包含非法字符或仅仅是空白(ArgumentException 类)。使用 Path 类创建有效路径名。
要创建的文件夹的父文件夹是只读的(IOException 类)。
文件夹名称是 null(ArgumentNullException 类)。
文件夹名称太长(PathTooLongException 类)。
文件夹名称只是冒号“:”(PathTooLongException 类)。