C# 如何:复制、删除和移动文件和文件夹

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

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


C 如何:复制、删除和移动文件和文件夹 - king5439 - king5439的技术空间 示例

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


C#

Copy Code

// Simple synchronous file copy operations with no user interface.  // To run this sample, first create the following directories and files:  // C:\Users\Public\TestFolder  // C:\Users\Public\TestFolder\test.txt  // C:\Users\Public\TestFolder\SubDir\test.txt  public class SimpleFileCopy  {      static void Main()      {          string fileName = "test.txt";          string sourcePath = @"C:\Users\Public\TestFolder";          string targetPath =  @"C:\Users\Public\TestFolder\SubDir";            // 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();      }  }

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


C#

Copy Code

// Simple synchronous file move operations with no user interface.  public class SimpleFileMove  {      static void Main()      {          string sourceFile = @"C:\Users\Public\public\test.txt";          string destinationFile = @"C:\Users\Public\private\test.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:\Users\Public\public\test\", @"C:\Users\Public\private");      }  }

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


C#

Copy Code

// Simple synchronous file deletion operations with no user interface.  // To run this sample, create the following files on your drive:  // C:\Users\Public\DeleteTest\test1.txt  // C:\Users\Public\DeleteTest\test2.txt  // C:\Users\Public\DeleteTest\SubDir\test2.txt    public class SimpleFileDelete  {      static void Main()      {          // Delete a file by using File class static method...          if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))          {              // Use a try block to catch IOExceptions, to              // handle the case of the file already being              // opened by another process.              try              {                  System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");              }              catch (System.IO.IOException e)              {                  Console.WriteLine(e.Message);                  return;              }          }            // ...or by using FileInfo instance method.          System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt");          try          {              fi.Delete();          }          catch (System.IO.IOException e)          {              Console.WriteLine(e.Message);          }            // Delete a directory. Must be writable or empty.          try          {              System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest");          }          catch (System.IO.IOException e)          {              Console.WriteLine(e.Message);          }          // Delete a directory and all subdirectories with Directory static method...          if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest"))          {              try              {                  System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true);              }                catch (System.IO.IOException e)              {                  Console.WriteLine(e.Message);              }          }            // ...or with DirectoryInfo instance method.          System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\Users\Public\public");          // Delete this dir and all subdirs.          try          {              di.Delete(true);          }          catch (System.IO.IOException e)          {              Console.WriteLine(e.Message);          }        }  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值