How to delete a file after checking whether it exists

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

提交回复
热议问题