How to delete a file after checking whether it exists

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

提交回复
热议问题