2013-01-04 5 views
8

저는 C#에서 WPF 응용 프로그램을 작성 중이며 일부 파일을 옮길 필요가 있습니다. 파일을 만들면 정말로 알아야 할 필요가 있습니다.System.IO.File.Move - 이동 완료를 기다리는 방법?

System.IO.File.Move(file.FullName, endLocationWithFile); 

      System.IO.FileInfo[] filesInDirectory = endLocation.GetFiles(); 
      foreach (System.IO.FileInfo temp in filesInDirectory) 
      { 
       if (temp.Name == shortFileName) 
       { 

        return true; 
       } 
      } 

      // The file we sent over has not gotten to the correct directory....something went wrong! 
      throw new IOException("File did not reach destination"); 

     } 
     catch (Exception e) 
     { 
      //Something went wrong, return a fail; 
      logger.writeErrorLog(e); 
      return false; 
     } 

누군가 말할 수 없습니다 : -이를 위해, 나는 파일이 이동 한 후 대상 디렉토리에 도달 있는지 확인합니다 수표를 쓴 문제는 파일이 이동 완료되기 전에 가끔 체크에 도착한다는 것입니다 파일이 실제로 목적지에 도착하는지 확인하는 방법 - 내가 이동할 파일은 매우 클 수 있습니다 - (최대 2 시간의 풀 HD mp4 파일)

고마워요!

+2

방법이 스트림을 복사하는 대신에'Move'를 사용하여 자신을 이동 관리에 대한? 그 때 무슨 일이 일어나는지 정확하게 알 수 있습니다. – spender

+0

훌륭한 사운드 ....그것을하는 방법에 대한 약간의 정보가있는 링크를 게시 할 수 있습니까? – Mizmor

+0

당신을 도울 답변을 추가했습니다. – spender

답변

7

당신은 파일이 완전히 같은

뭔가 작업을해야

을 복사하기 위해 Aysnc Await로 스트림을 사용할 수 있습니다 귀하의 사용 VS2010은 사용할 Async CTP을 설치해야합니다 경우

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    string sourceFile = @"\\HOMESERVER\Development Backup\Software\Microsoft\en_expression_studio_4_premium_x86_dvd_537029.iso"; 
    string destinationFile = "G:\\en_expression_studio_4_premium_x86_dvd_537029.iso"; 

    MoveFile(sourceFile, destinationFile); 
} 

private async void MoveFile(string sourceFile, string destinationFile) 
{ 
    try 
    { 
     using (FileStream sourceStream = File.Open(sourceFile, FileMode.Open)) 
     { 
      using (FileStream destinationStream = File.Create(destinationFile)) 
      { 
       await sourceStream.CopyToAsync(destinationStream); 
       if (MessageBox.Show("I made it in one piece :), would you like to delete me from the original file?", "Done", MessageBoxButton.YesNo) == MessageBoxResult.Yes) 
       { 
        sourceStream.Close(); 
        File.Delete(sourceFile); 
       } 
      } 
     } 
    } 
    catch (IOException ioex) 
    { 
     MessageBox.Show("An IOException occured during move, " + ioex.Message); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show("An Exception occured during move, " + ex.Message); 
    } 
} 

을 새로운 Async/Await 구문

+0

이것은 정말 깨끗한 해결책입니다 - 감사합니다! – Mizmor

+0

'if '가'using' 안에있는 이유는 무엇입니까? 즉,'if (MessageBox.Show (...)) File.Delete (sourceFile);'블록 둘 다 사용하지 않는 이유는 무엇입니까? (더 나은 것은'bool deleteSource = true' 인수를 포함하십시오.) –

+0

둘 다 똑같은 방식으로 작동하며,'사용하는 '내부의'if'는 아무런 차이가 없기 때문에'using' 문은 스트림에 dispose가 호출되고'if' 문과 아무 관련이 없으면 코드를 100 가지 방법으로 작성하고 동일한 효과를 얻을 수 있습니다. –

1

원본 디렉터리에서 파일이 사라지는 것을 확인한 다음 실제로 대상 디렉터리에 나타나는지 확인할 수 있습니다.

나는 파일 전문가에 대한 좋은 경험이 없습니다. 나는 대체로 쓰레드가 AutoResetEvent 일 때까지 기다리는 쓰레드를 가지고있을 것이지만, 별도의 쓰레드 나 타이머가 실행되어 주기적으로 원래 위치에서 파일이 사라지는 지 확인하고, 새 위치에 있는지 그리고 아마도 (당신의 환경과 필요) 파일의 일관성 검사 (예 : MD5 검사)를 수행합니다. 이러한 조건이 충족되면 "검사기"스레드/타이머가 원래 스레드가 진행될 수 있도록 AutoResetEvent를 트리거합니다.

"검사기"에 "너무 오래 걸리는"논리가 포함됩니다.

0

이동을 별도의 스레드에서 수행하여 응용 프로그램 실행을 몇 시간 동안 중단하지 않으려는 경우가 대부분입니다.

이동이 완료되지 않은 상태에서 프로그램을 계속 진행할 수없는 경우 대화 상자를 열고 이동 스레드에서 주기적으로 확인하여 진행 추적 프로그램을 업데이트 할 수 있습니다. 이것은 사용자에게 피드백을 제공하고 마치 프로그램이 멈춘 것처럼 느끼지 못하게합니다. http://hintdesk.com/c-wpf-copy-files-with-progress-bar-by-copyfileex-api/

1

왜 스트림을 복사하여 사본을 직접 관리하지 : 여기에 대한 정보와 예

있다?

//http://www.dotnetthoughts.net/writing_file_with_non_cache_mode_in_c/ 
const FileOptions FILE_FLAG_NO_BUFFERING = (FileOptions) 0x20000000; 

//experiment with different buffer sizes for optimal speed 
var bufLength = 4096; 

using(var outFile = 
    new FileStream(
     destPath, 
     FileMode.Create, 
     FileAccess.Write, 
     FileShare.None, 
     bufLength, 
     FileOptions.WriteThrough | FILE_FLAG_NO_BUFFERING)) 
using(var inFile = File.OpenRead(srcPath)) 
{ 
    //either 
    //inFile.CopyTo(outFile); 

    //or 
    var fileSizeInBytes = inFile.Length; 
    var buf = new byte[bufLength]; 
    long totalCopied = 0L; 
    int amtRead; 
    while((amtRead = inFile.Read(buf,0,bufLength)) > 0) 
    { 
     outFile.Write(buf,0,amtRead); 
     totalCopied += amtRead; 
     double progressPct = 
      Convert.ToDouble(totalCopied) * 100d/fileSizeInBytes; 
     progressPct.Dump(); 
    } 
} 
//file is written 
0

주기적으로 백그라운드 작업에서 copi ed 파일 크기가 원래 파일의 파일 크기에 도달했습니다 (파일간에 비교할 수있는 해시를 추가 할 수 있음).

0

최근에 비슷한 문제가 있습니다.

는 기다리지 않는다 이 이벤트에 반응

OnBackupStarts(); 
//.. do stuff 

new TaskFactory().StartNew(() => 
       { 
        OnBackupStarts() 
        //.. do stuff 
        OnBackupEnds(); 
       }); 


void OnBackupEnds() 
    { 
     if (BackupChanged != null) 
     { 
      BackupChanged(this, new BackupChangedEventArgs(BackupState.Done)); 
     } 
    } 

관련 문제