FileSystemWatcher 사용시
파일이 생성될 때(복사가 끝났을 경우) 작업을 해야하는 경우가 있는데
이 파일의 사이즈가 클 경우 문제가 발생할 수 있다.
FileSystemWatcher Class에는 복사완료에 대한 Event가 존재하지 않기 때문에
복사가 완료되지 않은 상태에서 이 파일을 읽고 작업을 하면 당연히 오류가 발생한다.
아래코드는 이런사항을 해결하기 위한 코드이다.
1 while (true)
2 {
3 try
4 {
5 using (Stream stream = System.IO.File.Open(e.FullPath,
6 FileMode.Open,
7 FileAccess.ReadWrite,
8 FileShare.ReadWrite))
9 {
10 if (stream != null)
11 {
12 System.Diagnostics.Trace.WriteLine(
13 string.Format("Output file {0} ready.", e.FullPath));
14 break;
15 }
16 }
17 }
18 catch (FileNotFoundException ex)
19 {
20 System.Diagnostics.Trace.WriteLine(
21 string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
22 }
23 catch (IOException ex)
24 {
25 System.Diagnostics.Trace.WriteLine(
26 string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
27 }
28 catch (UnauthorizedAccessException ex)
29 {
30 System.Diagnostics.Trace.WriteLine(
31 string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
32 }
33
34 System.Threading.Thread.Sleep(500);
35 }
퍼옴 : http://pino93.tistory.com/entry/C-FileSystemWatcher-OnCreated-Function%EC%9D%98-%EC%9D%BC%EB%B6%80
'.NET > C#.NET' 카테고리의 다른 글
IEnumerable을 지원할 경우 Linq활용 (0) | 2014.03.18 |
---|---|
[펌] C#] GetType의 활용 (0) | 2014.02.24 |
BackgroundWorker 사용 방법 입니다. (0) | 2014.01.23 |
멀티 쓰레드 구현 (0) | 2014.01.23 |
[펌]C# FileSystemWatcher + delegate 활용 (0) | 2013.12.04 |