반응형
public static bool IsFileLocked(string filePath)
{
return IsFileLocked(new FileInfo(filePath));
}
public static bool IsFileLocked(FileInfo file)
{
try
{
using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (IOException)
{
return true;
}
return false;
}
public static bool DeleteFile(string filePath)
{
try
{
if (!File.Exists(filePath)) return false;
int count = 0;
while (true)
{
if (IsFileLocked(filePath))
{
Thread.Sleep(100);
}
else
{
break;
}
// wait until 2sec
if (count++ > 20)
{
return false;
}
}
File.Delete(filePath);
}
catch (Exception)
{
return false;
}
return true;
}
반응형
'[====== Development ======] > C#' 카테고리의 다른 글
[C#] 중복 실행 방지 (0) | 2021.08.13 |
---|---|
[C#] 윈도우 시작 프로그램에 등록하기 (0) | 2021.08.13 |
파일 복사시 Unique 이름으로 저장 (0) | 2021.08.06 |
C# -> C++ MFC SendMessage string (0) | 2021.08.05 |
[Winform] textbox에 숫자만 입력 되도록 제한하는 코드 (0) | 2021.08.04 |