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

2019-12-26 17:37:11刘景俊


using (System.IO.FileStream fs = new System.IO.FileStream(pathString, FileMode.Append)) 
{
  for (byte i = 0; i < 100; i++)
  {
    fs.WriteByte(i);
  }
}

运行该示例若干次以验证数据是否每次都添加到文件中。

 

复制、删除和移动文件和文件夹
以下示例说明如何使用 System.IO 命名空间中的 System.IO.File、System.IO.Directory、System.IO.FileInfo 和 System.IO.DirectoryInfo 类以同步方式复制、移动和删除文件和文件夹。 这些示例没有提供进度栏或其他任何用户界面。 

示例
下面的示例演示如何复制文件和目录。


public class SimpleFileCopy
{
  static void Main()
  {
    string fileName = "test.txt";
    string sourcePath = @"C:UsersPublicTestFolder";
    string targetPath = @"C:UsersPublicTestFolderSubDir";

    // Use Path class to manipulate file and directory paths.
    string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
    string destFile = System.IO.Path.Combine(targetPath, fileName);

    // To copy a folder's contents to a new location:
    // Create a new target folder, if necessary.
    if (!System.IO.Directory.Exists(targetPath))
    {
      System.IO.Directory.CreateDirectory(targetPath);
    }

    // To copy a file to another location and 
    // overwrite the destination file if it already exists.
    System.IO.File.Copy(sourceFile, destFile, true);

    // To copy all the files in one directory to another directory.
    // Get the files in the source folder. (To recursively iterate through
    // all subfolders under the current directory, see
    // "How to: Iterate Through a Directory Tree.")
    // Note: Check for target path was performed previously
    //    in this code example.
    if (System.IO.Directory.Exists(sourcePath))
    {
      string[] files = System.IO.Directory.GetFiles(sourcePath);

      // Copy the files and overwrite destination files if they already exist.
      foreach (string s in files)
      {
        // Use static Path methods to extract only the file name from the path.
        fileName = System.IO.Path.GetFileName(s);
        destFile = System.IO.Path.Combine(targetPath, fileName);
        System.IO.File.Copy(s, destFile, true);
      }
    }
    else
    {
      Console.WriteLine("Source path does not exist!");
    }

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


下面的示例演示如何移动文件和目录。


public class SimpleFileMove
{
  static void Main()
  {
    string sourceFile = @"C:UsersPublicpublictest.txt";
    string destinationFile = @"C:UsersPublicprivatetest.txt";

    // To move a file or folder to a new location:
    System.IO.File.Move(sourceFile, destinationFile);

    // To move an entire directory. To programmatically modify or combine
    // path strings, use the System.IO.Path class.
    System.IO.Directory.Move(@"C:UsersPublicpublictest", @"C:UsersPublicprivate");
  }
}