【问题标题】:How to delete a file after checking whether it exists检查文件是否存在后如何删除
【发布时间】:2011-09-17 12:22:14
【问题描述】:

如何在 C# 中删除文件,例如C:\test.txt,虽然应用了与批处理文件中相同的方法,例如

if exist "C:\test.txt"

delete "C:\test.txt"

else 

return nothing (ignore)

【问题讨论】:

    标签: c# .net windows


    【解决方案1】:

    使用File 类非常简单。

    if(File.Exists(@"C:\test.txt"))
    {
        File.Delete(@"C:\test.txt");
    }
    


    正如 Chris 在 cmets 中指出的那样,您实际上不需要进行 File.Exists 检查,因为如果文件不存在,File.Delete 不会引发异常,尽管如果您使用的是绝对路径,您将需要检查以确保整个文件路径有效。

    【讨论】:

    • 实际上不需要该测试。看我的帖子。
    • 如果你想防止可能的 DirectoryNotFoundException,测试是必要的。
    • 测试不应该用来代替异常处理,而应该用来处理它。任意数量的场景都可能导致存在检查返回 true 并引发删除。
    • 为什么文件路径前有@?对我来说,它没有。
    • @ 使您不必将反斜杠加倍。
    【解决方案2】:

    像这样使用System.IO.File.Delete

    System.IO.File.Delete(@"C:\test.txt")

    来自文档:

    如果要删除的文件不存在,则不抛出异常。

    【讨论】:

    • 如果“指定的路径无效(例如,它位于未映射的驱动器上),则会抛出 DirectoryNotFoundException。”
    • 多么奇怪。 Intellisense 说An exception is thrown if the specified file does not exist
    • 也许您使用的是不同版本的 .NET 框架?
    • 我使用的是 .Net4,看来智能感知是错误的 我已经运行检查,没有抛出异常
    • 是的,我试过了,System.IO.File.Delete(@"C:\test.txt"); 就足够了。谢谢
    【解决方案3】:

    您可以使用以下方法导入 System.IO 命名空间:

    using System.IO;
    

    如果filepath代表文件的完整路径,可以检查其是否存在并删除,如下:

    if(File.Exists(filepath))
    {
         try
        {
             File.Delete(filepath);
        } 
        catch(Exception ex)
        {
          //Do something
        } 
    }  
    

    【讨论】:

    • 为什么不直接发出 Delete 调用并捕获任何表明文件不存在的异常?
    • 我想还有更多可以抛出的异常。
    【解决方案4】:
    if (System.IO.File.Exists(@"C:\test.txt"))
        System.IO.File.Delete(@"C:\test.txt"));
    

    但是

    System.IO.File.Delete(@"C:\test.txt");
    

    只要文件夹存在,就会这样做。

    【讨论】:

      【解决方案5】:

      如果你想避免DirectoryNotFoundException,你需要确保文件的目录确实存在。 File.Exists 实现了这一点。另一种方法是使用PathDirectory 实用程序类,如下所示:

      string file = @"C:\subfolder\test.txt";
      if (Directory.Exists(Path.GetDirectoryName(file)))
      {
          File.Delete(file);
      }
      

      【讨论】:

        【解决方案6】:
          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;
                }
            }
        

        【讨论】:

          【解决方案7】:
          if (File.Exists(path))
          {
              File.Delete(path);
          }
          

          【讨论】:

            【解决方案8】:

            如果您正在使用 FileStream 读取该文件,然后想要删除它,请确保在调用 File.Delete(path) 之前关闭 FileStream。我遇到了这个问题。

            var filestream = new System.IO.FileStream(@"C:\Test\PutInv.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
            filestream.Close();
            File.Delete(@"C:\Test\PutInv.txt");
            

            【讨论】:

            • 或使用using 语句,其中File.Delete() 将超出括号。在您的示例中,您还应该执行filestream.Dispose();
            【解决方案9】:

            有时你想删除一个文件(无论发生什么异常,请务必删除该文件)。对于这种情况。

            public static void DeleteFile(string path)
                    {
                        if (!File.Exists(path))
                        {
                            return;
                        }
            
                        bool isDeleted = false;
                        while (!isDeleted)
                        {
                            try
                            {
                                File.Delete(path);
                                isDeleted = true;
                            }
                            catch (Exception e)
                            {
                            }
                            Thread.Sleep(50);
                        }
                    }
            

            注意:如果指定的文件不存在,不会抛出异常。

            【讨论】:

            • 所以你试图每秒删除文件 20 次,直到它被删除。如果由于某种原因无法删除文件并且程序会尝试永远删除它怎么办?我认为这不是一个好的解决方案。
            • 至少,你应该提供一个超时参数。
            • @kv1dr 对。如果文件没有被删除,我认为你应该在有限的时间内尝试并返回失败消息。
            【解决方案10】:
            if (File.Exists(Path.Combine(rootFolder, authorsFile)))    
            {    
            // If file found, delete it    
            File.Delete(Path.Combine(rootFolder, authorsFile));    
            Console.WriteLine("File deleted.");    
            } 
            

            动态

             string FilePath = Server.MapPath(@"~/folder/news/" + IdSelect)
             if (System.IO.File.Exists(FilePath + "/" + name+ ".jpg"))
               {
                System.IO.File.Delete(FilePath + "/" + name+ ".jpg");
               }
            

            删除目录中的所有文件

            string[] files = Directory.GetFiles(rootFolder);    
            foreach (string file in files)    
            {    
            File.Delete(file);    
            Console.WriteLine($"{file} is deleted.");    
            }
            

            【讨论】:

              【解决方案11】:

              这将是最简单的方法,

              if (System.IO.File.Exists(filePath)) 
              {
                System.IO.File.Delete(filePath);
                System.Threading.Thread.Sleep(20);
              }
              

              Thread.sleep 将有助于完美工作,否则如果我们复制或写入文件将影响下一步。

              我做的另一种方法是,

              if (System.IO.File.Exists(filePath))
              {
              System.GC.Collect();
              System.GC.WaitForPendingFinalizers();
              System.IO.File.Delete(filePath);
              }
              

              【讨论】:

                猜你喜欢
                • 2017-10-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-07-30
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-02-10
                相关资源
                最近更新 更多