How to delete a file after checking whether it exists

后端 未结 10 1787
盖世英雄少女心
盖世英雄少女心 2020-11-30 19:50

How can I delete a file in C# e.g. C:\\test.txt, although apply the same kind of method like in batch files e.g.

if exist \"C:\\test.txt\"

dele         


        
相关标签:
10条回答
  • 2020-11-30 20:32
    if (File.Exists(path))
    {
        File.Delete(path);
    }
    
    0 讨论(0)
  • 2020-11-30 20:33

    If you want to avoid a DirectoryNotFoundException you will need to ensure that the directory of the file does indeed exist. File.Exists accomplishes this. Another way would be to utilize the Path and Directory utility classes like so:

    string file = @"C:\subfolder\test.txt";
    if (Directory.Exists(Path.GetDirectoryName(file)))
    {
        File.Delete(file);
    }
    
    0 讨论(0)
  • 2020-11-30 20:33

    This will be the simplest way,

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

    Thread.sleep will help to work perfectly, otherwise, it will affect the next step if we doing copy or write the file.

    Another way I did is,

    if (System.IO.File.Exists(filePath))
    {
    System.GC.Collect();
    System.GC.WaitForPendingFinalizers();
    System.IO.File.Delete(filePath);
    }
    
    0 讨论(0)
  • Sometimes you want to delete a file whatever the case(whatever the exception occurs ,please do delete the file). For such situations.

    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);
                }
            }
    

    Note:An exception is not thrown if the specified file does not exist.

    0 讨论(0)
提交回复
热议问题