|
此示例在計(jì)算機(jī)上創(chuàng)建一個(gè)文件夾和一個(gè)子文件夾,然后在該子文件夾中創(chuàng)建一個(gè)新文件并將一些數(shù)據(jù)寫入該文件。 示例
public class CreateFileOrFolder
{ static void Main() { // Specify a "currently active folder" string activeDir = @"d:\testdir"; //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 不執(zhí)行任何操作,且不會(huì)引發(fā)異常。而 File.Create 則會(huì)覆蓋任何現(xiàn)有文件。若要避免覆蓋現(xiàn)有文件,可以使用 OpenWrite() 方法并指定將使文件被追加而不是被覆蓋的 FileMode.OpenOrCreate 選項(xiàng)。 以下情況可能會(huì)導(dǎo)致異常:
安全性
在部分信任的情況下可能會(huì)引發(fā) SecurityException 類的實(shí)例。 如果用戶不具有創(chuàng)建文件夾的權(quán)限,則該示例引發(fā) UnauthorizedAccessException 類的實(shí)例。 |
|
|
來(lái)自: *我愛陽(yáng)光* > 《我的圖書館》