How to delete a file after checking whether it exists

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

提交回复
热议问题