파일이 있는지 확인한 후 파일을 삭제하는 방법 파일과 같은

C:\test.txt배치 파일과 같은 종류의 방법을 적용하지만 C #에서 파일을 어떻게 삭제할 수 있습니까?

if exist "C:\test.txt"

delete "C:\test.txt"

else

return nothing (ignore)


답변

File 클래스를 사용하면 매우 간단합니다 .

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

크리스는 의견에서 지적, 당신은 실제로 수행 할 필요가 없습니다 File.Exists이후 확인 File.Delete파일이 존재하지 않는 경우 절대 경로를 사용하는 경우 확인을 위해 검사가 필요하지만, 예외를 throw하지 않습니다 전체 파일 경로가 유효합니다.


답변

System.IO.File.Delete를 다음 과 같이 사용하십시오 .

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

설명서에서 :

삭제할 파일이 없으면 예외가 발생하지 않습니다.


답변

다음을 System.IO사용 하여 네임 스페이스를 가져올 수 있습니다 .

using System.IO;

파일 경로가 파일의 전체 경로를 나타내는 경우 파일의 존재를 확인하고 다음과 같이 삭제할 수 있습니다.

if(File.Exists(filepath))
{
     try
    {
         File.Delete(filepath);
    }
    catch(Exception ex)
    {
      //Do something
    }
}  

답변

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

그러나

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

폴더가 존재하는 한 동일하게 수행됩니다.


답변

를 피 DirectoryNotFoundException하려면 파일의 디렉토리가 실제로 존재하는지 확인해야합니다. File.Exists이것을 달성합니다. 또 다른 방법은 다음 PathDirectory같이 및 유틸리티 클래스 를 활용하는 것입니다 .

string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
    File.Delete(file);
}

답변

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