본문 바로가기

프로그래밍/C#

UnauthorizedAccessException 발생 - 읽기전용 파일 삭제

[Normal]UnauthorizedAccessException : '181101-1653391-1.pdf' 경로에 대한 액세스가 거부되었습니다.

PDF 파일을 JPG로 변환 중 UnauthorizedAccessException이 발생 됨.

UnauthorizedAccessException 는 4 가지 중 하나를 의미합니다.

  • 호출자에게 필요한 권한이 없습니다.
  • 이 파일은 사용중인 실행 파일입니다.
  • 경로는 디렉토리입니다.
  • 경로가 읽기 전용 파일을 지정했습니다.

※출처 : https://code.i-harness.com/ko-kr/q/869aa2

위 내용 중 먼저, 해당 파일이 읽기전용 파일인지 확인해보았습니다.

읽기전용이었습니다.

그래서 아래와 같이 ReadOnly속성을 Nomal로 바꿔주니, 삭제가 잘되었습니다.

catch (UnauthorizedAccessException ex)
{
    LogWriter.NomalLog($"UnauthorizedAccessException : {ex.Message}, {item.Name}");
    if ((item.Attributes & FileAttributes.ReadOnly) > 0)
    {
        LogWriter.NomalLog($"{item} = 읽기전용 해제 후 삭제");
        item.Attributes = FileAttributes.Normal;
    }
    item.Delete();
}