C#

파일 사용중인지 확인

탑~! 2016. 2. 25. 11:22


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

}




출처 : http://kimstar.kr/5990/

728x90
반응형