파일이 있는지 확인한 후 파일을 삭제하는 방법
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")
설명서에서 :
삭제할 파일이 없으면 예외가 발생하지 않습니다.
if (System.IO.File.Exists(@"C:\test.txt"))
System.IO.File.Delete(@"C:\test.txt"));
그러나
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
}
}
를 피 DirectoryNotFoundException
하려면 파일의 디렉토리가 실제로 존재하는지 확인해야합니다. File.Exists
이것을 달성합니다. 또 다른 방법은 다음 Path
과 Directory
같이 및 유틸리티 클래스 를 활용하는 것입니다 .
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;
}
}
if (File.Exists(path))
{
File.Delete(path);
}
FileStream을 사용하여 해당 파일에서 읽은 후 삭제하려면 File.Delete (path)를 호출하기 전에 FileStream을 닫아야합니다. 나는이 문제가 있었다.
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");
때로는 어떤 경우이든 파일을 삭제하려고합니다 (예외가 발생하면 파일을 삭제하십시오). 그런 상황에.
public static void DeleteFile(string path)
{
if (!File.Exists(path))
{
return;
}
bool isDeleted = false;
while (!isDeleted)
{
try
{
File.Delete(path);
isDeleted = true;
}
catch (Exception e)
{
}
Thread.Sleep(50);
}
}
참고 : 지정된 파일이 없으면 예외가 발생하지 않습니다.
이것이 가장 간단한 방법입니다.
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
System.Threading.Thread.Sleep(20);
}
Thread.sleep
완벽하게 작동하는 데 도움이됩니다. 그렇지 않으면 파일을 복사하거나 쓰면 다음 단계에 영향을줍니다.
참고URL : https://stackoverflow.com/questions/6391711/how-to-delete-a-file-after-checking-whether-it-exists
'Programing' 카테고리의 다른 글
string [] 배열에 문자열을 추가하는 방법? (0) | 2020.05.08 |
---|---|
이메일 주소가 iOS에서 유효한지 확인하십시오 (0) | 2020.05.08 |
뷰에서 현재 컨트롤러의 이름을 얻을 수 있습니까? (0) | 2020.05.08 |
파이썬 패키지를 어떻게 업데이트합니까? (0) | 2020.05.08 |
jQuery로 DIV 배경 이미지 전환 (0) | 2020.05.08 |