2016-05-12 27 views
0

當然有許多類似於我的問題,但沒有一個真正回答我的問題或提出它爲什麼在調試中起作用的問題不在運行時。正在執行file.copy異常拋出無法訪問正在使用的文件,編譯時調試時編譯時不起作用

我做了一個FileSystemWatcher,它等待在我的服務器上的目錄中創建一個文件。 引發一個Event,然後拾取文件名稱,並將其複製到.csv的另一個目錄中。 雖然一步一步的調試,當我編譯它時破壞試圖File.copy()

class Program 
{ 
    public static string AdresaEXD { get; set; } 
    public static string AdresaCSV { get; set; } 
    public static string IzvorniFajl { get; set; } //source file 
    public static string KreiraniFajl { get; set; }// renamed file 

    static void Main(string[] args) 
    { 
     GledanjeFoldera();/ watcher 
    } 

    static void GledanjeFoldera() 
    { 
     AdresaEXD = @"H:\CRT_FOR_FIS\EXD"; 
     AdresaCSV = @"H:\CRT_FOR_FIS\CSV"; 

     FileSystemWatcher CRT_gledaj = new FileSystemWatcher(AdresaEXD,"*.exd"); 

     // Making filters 

     CRT_gledaj.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName; 

     // create event handler 

     CRT_gledaj.Created += new FileSystemEventHandler(ObradaITransformacijaEXD); 

     // starting to watch 

     CRT_gledaj.EnableRaisingEvents = true; 

     // loop 

     Console.WriteLine("Ako zelite da prekinete program pritisnite \'q\'."); 

     while (Console.ReadLine() != "q"); 


    } 

    private static void ObradaITransformacijaEXD(object source, FileSystemEventArgs e) // 
    { 

     // 
     string NoviFajl = e.Name.Remove(e.Name.Length-4,4)+".csv";// new file name 

     // create paths 
     IzvorniFajl = System.IO.Path.Combine(AdresaEXD, e.Name); 
     KreiraniFajl = System.IO.Path.Combine(AdresaCSV, e.Name); 


     // copy file to other destination and delete after 
     System.IO.File.Copy(IzvorniFajl, KreiraniFajl, true); 
     System.IO.File.Delete(IzvorniFajl); 


    } 
} 

回答

1

問題是FileSystemWatcher事件在文件開始創建時觸發。請嘗試以下操作:

private static bool IsFileLocked(FileInfo file) 
    { 
     FileStream stream = null; 

     try 
     { 
      stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
     } 
     catch (IOException) 
     { 
      return true; 
     } 
     finally 
     { 
      if (stream != null) 
       stream.Close(); 
     } 

     //file is not locked 
     return false; 
    } 

如果正在使用該文件,則此函數返回true。所以,你可以像這樣

while (IsFileLocked(new FileInfo(eventArgs.FullPath))) { } 

一個循環,待退出循環複製的文件

相關問題