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

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


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


public class SimpleFileDelete
{
  static void Main()
  {
    // Delete a file by using File class static method...
    if(System.IO.File.Exists(@"C:UsersPublicDeleteTesttest.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:UsersPublicDeleteTesttest.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:UsersPublicDeleteTesttest2.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:UsersPublicDeleteTest");
    }
    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:UsersPublicDeleteTest"))
    {
      try
      {
        System.IO.Directory.Delete(@"C:UsersPublicDeleteTest", true);
      }

      catch (System.IO.IOException e)
      {
        Console.WriteLine(e.Message);
      }
    }

    // ...or with DirectoryInfo instance method.
    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:UsersPublicpublic");
    // Delete this dir and all subdirs.
    try
    {
      di.Delete(true);
    }
    catch (System.IO.IOException e)
    {
      Console.WriteLine(e.Message);
    }

  }
}


注:相关教程知识阅读请移步到c#教程频道。