复制、删除和移动文件和文件夹(C# 编程指南)

本文详细介绍了使用C#中的System.IO命名空间进行文件操作的方法,包括同步复制、移动和删除文件及目录。提供了复制单个文件、复制整个目录、移动文件和目录、删除文件和目录的具体示例,帮助开发者高效地管理和操作文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下示例说明如何使用 System.IO 命名空间中的 System.IO..::.FileSystem.IO..::.DirectorySystem.IO..::.FileInfoSystem.IO..::.DirectoryInfo 类以同步方式复制、移动和删除文件和文件夹。 这些示例没有提供进度栏或其他任何用户界面。 如果您想提供一个标准进度对话框,请参见如何:提供文件操作进度对话框(C# 编程指南)

在操作多个文件时,请使用 System.IO..::.FileSystemWatcher 提供一些事件,以便可以利用这些事件计算进度。 另一种方法是使用平台调用来调用 Windows Shell 中相应的文件相关方法。 有关如何异步执行这些文件操作的信息,请参见异步文件 I/O

示例

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


      
  1. // Simple synchronous file copy operations with no user interface.
  2. // To run this sample, first create the following directories and files:
  3. // C:/Users/Public/TestFolder
  4. // C:/Users/Public/TestFolder/test.txt
  5. // C:/Users/Public/TestFolder/SubDir/test.txt
  6. public class SimpleFileCopy
  7. {
  8.     static void Main()
  9.     {
  10.         string fileName = "test.txt";
  11.         string sourcePath = @"C:/Users/Public/TestFolder";
  12.         string targetPath =  @"C:/Users/Public/TestFolder/SubDir";
  13.  
  14.         // Use Path class to manipulate file and directory paths.
  15.         string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
  16.         string destFile = System.IO.Path.Combine(targetPath, fileName);
  17.  
  18.         // To copy a folder's contents to a new location:
  19.         // Create a new target folder, if necessary.
  20.         if (!System.IO.Directory.Exists(targetPath))
  21.         {
  22.             System.IO.Directory.CreateDirectory(targetPath);
  23.         }
  24.  
  25.         // To copy a file to another location and 
  26.         // overwrite the destination file if it already exists.
  27.         System.IO.File.Copy(sourceFile, destFile, true);
  28.  
  29.         // To copy all the files in one directory to another directory.
  30.         // Get the files in the source folder. (To recursively iterate through
  31.         // all subfolders under the current directory, see
  32.         // "How to: Iterate Through a Directory Tree.")
  33.         // Note: Check for target path was performed previously
  34.         //       in this code example.
  35.         if (System.IO.Directory.Exists(sourcePath))
  36.         {
  37.             string[] files = System.IO.Directory.GetFiles(sourcePath);
  38.  
  39.             // Copy the files and overwrite destination files if they already exist.
  40.             foreach (string s in files)
  41.             {
  42.                 // Use static Path methods to extract only the file name from the path.
  43.                 fileName = System.IO.Path.GetFileName(s);
  44.                 destFile = System.IO.Path.Combine(targetPath, fileName);
  45.                 System.IO.File.Copy(s, destFile, true);
  46.             }
  47.         }
  48.         else
  49.         {
  50.             Console.WriteLine("Source path does not exist!");
  51.         }
  52.  
  53.         // Keep console window open in debug mode.
  54.         Console.WriteLine("Press any key to exit.");
  55.         Console.ReadKey();
  56.     }
  57. }
  58.  

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


      
  1. // Simple synchronous file move operations with no user interface.
  2. public class SimpleFileMove
  3. {
  4.     static void Main()
  5.     {
  6.         string sourceFile = @"C:/Users/Public/public/test.txt";
  7.         string destinationFile = @"C:/Users/Public/private/test.txt";
  8.  
  9.         // To move a file or folder to a new location:
  10.         System.IO.File.Move(sourceFile, destinationFile);
  11.  
  12.         // To move an entire directory. To programmatically modify or combine
  13.         // path strings, use the System.IO.Path class.
  14.         System.IO.Directory.Move(@"C:/Users/Public/public/test/", @"C:/Users/Public/private");
  15.     }
  16. }
  17.  

下面的示例演示如何删除文件和目录。


      
  1. // Simple synchronous file deletion operations with no user interface.
  2. // To run this sample, create the following files on your drive:
  3. // C:/Users/Public/DeleteTest/test1.txt
  4. // C:/Users/Public/DeleteTest/test2.txt
  5. // C:/Users/Public/DeleteTest/SubDir/test2.txt
  6.  
  7. public class SimpleFileDelete
  8. {
  9.     static void Main()
  10.     {
  11.         // Delete a file by using File class static method...
  12.         if(System.IO.File.Exists(@"C:/Users/Public/DeleteTest/test.txt"))
  13.         {
  14.             // Use a try block to catch IOExceptions, to
  15.             // handle the case of the file already being
  16.             // opened by another process.
  17.             try
  18.             {
  19.                 System.IO.File.Delete(@"C:/Users/Public/DeleteTest/test.txt");
  20.             }
  21.             catch (System.IO.IOException e)
  22.             {
  23.                 Console.WriteLine(e.Message);
  24.                 return;
  25.             }
  26.         }
  27.  
  28.         // ...or by using FileInfo instance method.
  29.         System.IO.FileInfo fi = new System.IO.FileInfo(@"C:/Users/Public/DeleteTest/test2.txt");
  30.         try
  31.         {
  32.             fi.Delete();
  33.         }
  34.         catch (System.IO.IOException e)
  35.         {
  36.             Console.WriteLine(e.Message);
  37.         }
  38.  
  39.         // Delete a directory. Must be writable or empty.
  40.         try
  41.         {
  42.             System.IO.Directory.Delete(@"C:/Users/Public/DeleteTest");
  43.         }
  44.         catch (System.IO.IOException e)
  45.         {
  46.             Console.WriteLine(e.Message);
  47.         }
  48.         // Delete a directory and all subdirectories with Directory static method...
  49.         if(System.IO.Directory.Exists(@"C:/Users/Public/DeleteTest"))
  50.         {
  51.             try
  52.             {
  53.                 System.IO.Directory.Delete(@"C:/Users/Public/DeleteTest"true);
  54.             }
  55.  
  56.             catch (System.IO.IOException e)
  57.             {
  58.                 Console.WriteLine(e.Message);
  59.             }
  60.         }
  61.  
  62.         // ...or with DirectoryInfo instance method.
  63.         System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:/Users/Public/public");
  64.         // Delete this dir and all subdirs.
  65.         try
  66.         {
  67.             di.Delete(true);
  68.         }
  69.         catch (System.IO.IOException e)
  70.         {
  71.             Console.WriteLine(e.Message);
  72.         }
  73.  
  74.     }
  75. }
  76.  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值