How to delete a file after checking whether it exists

后端 未结 10 1786
盖世英雄少女心
盖世英雄少女心 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:10

    If you are reading from that file using FileStream and then wanting to delete it, make sure you close the FileStream before you call the File.Delete(path). I had this issue.

    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");
    
    0 讨论(0)
  • 2020-11-30 20:13

    This is pretty straightforward using the File class.

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


    As Chris pointed out in the comments, you don't actually need to do the File.Exists check since File.Delete doesn't throw an exception if the file doesn't exist, although if you're using absolute paths you will need the check to make sure the entire file path is valid.

    0 讨论(0)
  • 2020-11-30 20:20
      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;
            }
        }
    
    0 讨论(0)
  • 2020-11-30 20:25

    You could import the System.IO namespace using:

    using System.IO;
    

    If the filepath represents the full path to the file, you can check its existence and delete it as follows:

    if(File.Exists(filepath))
    {
         try
        {
             File.Delete(filepath);
        } 
        catch(Exception ex)
        {
          //Do something
        } 
    }  
    
    0 讨论(0)
  • 2020-11-30 20:29

    Use System.IO.File.Delete like so:

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

    From the documentation:

    If the file to be deleted does not exist, no exception is thrown.

    0 讨论(0)
  • 2020-11-30 20:32
    if (System.IO.File.Exists(@"C:\test.txt"))
        System.IO.File.Delete(@"C:\test.txt"));
    

    but

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

    will do the same as long as the folder exists.

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