파일의 삭제/이동 등을 수행하기 전에 파일이 사용중인지 확인하는 메소드입니다.
/// <summary>
/// 파일이 다른 프로세스에 의해 사용중인지 점검
/// </summary>
/// <param name="filePath">파일경로</param>
/// <param name="secondsToWait">사용중이면 잠시 기다릴 시간</param>
/// <returns>사용중이면 true</returns>
public static bool IsFileLocked(string filePath, int secondsToWait)
{
bool isLocked = true;
int i = 0;
while (isLocked && ((i < secondsToWait) || (secondsToWait == 0)))
{
try
{
using (File.Open(filePath, FileMode.Open)) { }
return false;
}
catch (IOException e)
{
var errorCode = System.Runtime.InteropServices.Marshal.GetHRForException(e) & ((1 << 16) - 1);
isLocked = errorCode == 32 || errorCode == 33;
i++;
if (secondsToWait != 0)
new System.Threading.ManualResetEvent(false).WaitOne(1000);
}
}
return isLocked;
}
파일 삭제시 파일이 잠겨있는지 확인하고 처리하는 메소드는 아래와 같습니다.
/// <summary>
/// 파일을 삭제한다.
/// </summary>
public static void DeleteFile(string filePath)
{
if (string.IsNullOrEmpty(filePath)) return;
if (File.Exists(filePath) == false) return;
if (FileUtil.IsFileLocked(filePath, 1)) return;
File.Delete(filePath);
}


