2010-12-09 43 views

回答

9

下面的示例代碼將創建一個文件夾,並在你的C子文件夾創建一個使用C#在C驅動器中的文件創建一個使用C#在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(); 
    } 
} 

通過讀取original MSDN How-To article看到所有的血淋淋的細節。