C#程序中创建、复制、移动、删除文件或文件夹的示例

2019-12-26 17:37:11刘景俊
易采站长站为您分析C#程序中创建、复制、移动、删除文件或文件夹的示例,即对System.IO命名空间中类的运用,需要的朋友可以参考下  

创建文件或文件夹

您可通过编程方式在您的计算机上创建文件夹、子文件夹和子文件夹中的文件,并将数据写入文件。


public class CreateFileOrFolder
{
  static void Main()
  {
    string folderName = @"c:Top-Level Folder";

    string pathString = System.IO.Path.Combine(folderName, "SubFolder");

    string pathString2 = @"c:Top-Level FolderSubFolder2";

    System.IO.Directory.CreateDirectory(pathString);

 
    string fileName = System.IO.Path.GetRandomFileName();

    pathString = System.IO.Path.Combine(pathString, fileName);

    Console.WriteLine("Path to my file: {0}n", pathString);

    if (!System.IO.File.Exists(pathString))
    {
      using (System.IO.FileStream fs = System.IO.File.Create(pathString))
      {
        for (byte i = 0; i < 100; i++)
        {
          fs.WriteByte(i);
        }
      }
    }
    else
    {
      Console.WriteLine("File "{0}" already exists.", fileName);
      return;
    }

    try
    {
      byte[] readBuffer = System.IO.File.ReadAllBytes(pathString);
      foreach (byte b in readBuffer)
      {
        Console.Write(b + " ");
      }
      Console.WriteLine();
    }
    catch (System.IO.IOException e)
    {
      Console.WriteLine(e.Message);
    }

    System.Console.WriteLine("Press any key to exit.");
    System.Console.ReadKey();
  }

}

输出:
Path to my file: c:Top-Level FolderSubFolderttxvauxe.vv0


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 8
3 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

如果该文件夹已存在,则 CreateDirectory 不执行任何操作,且不会引发异常。但是,File.Create 用新的文件替换现有文件。该示例使用一个 if-else 语句阻止现有文件被替换。
通过在示例中做出以下更改,您可以根据具有某个名称的程序是否存在来指定不同的结果。如果该文件不存在,代码将创建一个文件。如果该文件存在,代码将把数据添加到该文件中。
指定一个非随机文件名。


// Comment out the following line.
//string fileName = System.IO.Path.GetRandomFileName();

// Replace that line with the following assignment.
string fileName = "MyNewFile.txt";

用以下代码中的 using 语句替换 if-else 语句。