2013-01-14 44 views
1

我有這樣的代碼正在被重複3次:文件編寫3次C#

private static void convert(object source, FileSystemEventArgs f) 
{ 
    string FileName; 
    FileName = f.FullPath; 

    string destinationFile = @"Y:\test\test.xml"; 
       System.Threading.Thread.Sleep(2000); 
    try 
    { 

     Encoding utf8 = new UTF8Encoding(false); 
     Encoding ansi = Encoding.GetEncoding(1256); 
     System.Threading.Thread.Sleep(2000); 

     string xml = File.ReadAllText(FileName, ansi); 
     XDocument xmlDoc = XDocument.Parse(xml); 
      **Console.WriteLine("1st");** 
      File.WriteAllText(
       destinationFile, 
       @"<?xml version=""1.0"" encoding=""utf-8""?>" + xmlDoc.ToString(), 
       utf8 
      ); 
    } 

檢查上面的粗體字。它寫出3次。我剛剛把這個測試。但爲什麼它寫出3次..意味着正在寫入的文件也被寫入3次。

我從文件系統監視器函數調用這個函數來觀察一個文件夾,如果它已經改變,然後把文件轉換爲utf-8並將其放入目標文件。編輯1: 這是我的守望者。您可以請檢查一下這是否正常:

private static void WatchFile() 
    { 
       watcher.Path = @"C:\project"; 

        watcher.NotifyFilter = NotifyFilters.LastWrite; 
     watcher.Filter = "*.xml"; 


     watcher.Changed += new FileSystemEventHandler(convert); 
     watcher.Error += new ErrorEventHandler(WatcherError); 
     Console.WriteLine("2nd"); 
     watcher.EnableRaisingEvents = true; 


    } 

仍然沒有線索爲什麼它重複3次。

編輯2:

這裏不用我的完整代碼:

using System; 
using System.IO; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 
using System.Collections.Generic; 
using System.Linq; 





class Test 
{ 
class Class1 
{ 
    private static FileSystemWatcher watcher = 
     new FileSystemWatcher(); 

    public static void Main() 
    { 
     WatchFile(); 
     Console.ReadLine(); 
    } 

    private static void WatchFile() 
    { 
     watcher.Path = @"C:\project"; 

        watcher.NotifyFilter = NotifyFilters.LastWrite; 
     watcher.Filter = "*.xml"; 


     watcher.Changed += new FileSystemEventHandler(convert); 
     watcher.Error += new ErrorEventHandler(WatcherError); 
     Console.WriteLine("2nd"); 
     watcher.EnableRaisingEvents = true; 

    } 

    public static string CrL = "\r\n"; 

    private static void convert(object source, FileSystemEventArgs f) 
    { 
     string FileName; 
     FileName = f.FullPath; 

       string destinationFile = @"Y:\test\OnAirNow.xml"; 

       System.Threading.Thread.Sleep(2000); 
     try 
     { 

      Encoding utf8 = new UTF8Encoding(false); 
      Encoding ansi = Encoding.GetEncoding(1256); 
      System.Threading.Thread.Sleep(2000); 

      string xml = File.ReadAllText(FileName, ansi); 
      XDocument xmlDoc = XDocument.Parse(xml); 
       Console.WriteLine("1st"); 
       File.WriteAllText(
        destinationFile, 
        @"<?xml version=""1.0"" encoding=""utf-8""?>" + xmlDoc.ToString(), 
        utf8 
       ); 



     } 
     catch (Exception e) 
     { 
      Console.WriteLine("The process failed: {0}", e.ToString()); 
     } 


    } 

    private static void WatcherError(object source, ErrorEventArgs e) 
    { 

     Exception watchException = e.GetException(); 
        watcher = new FileSystemWatcher(); 
     while (!watcher.EnableRaisingEvents) 
     { 
      try 
      { 
            WatchFile(); 
       Console.WriteLine("I'm Back!!"); 
      } 
      catch 
      { 
            System.Threading.Thread.Sleep(2000); 
      } 
     } 
    } 


    } 
} 
+7

有這個方法沒有循環,所以問題不在這裏。問題出現在調用此方法的代碼中(多個FSW事件觸發?) – Bridge

+0

我用我的觀察器編輯過。你可以檢查一下這是否正常 – user726720

+0

filesystemwatcher函數可能會多次調用函數'convert(object source,FileSystemEventArgs f)'。如果你給我們多一點關於文件監視器的代碼,我們可能會更有幫助。 – anthares

回答

3

使用FileSystemWatcher是設置EnableRaisingEventsfalse開始處理事件時,一個常見的模式:

this.fileSystemWatcher = new FileSystemWatcher() 
{ 
    Path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, 
    NotifyFilter = NotifyFilters.LastWrite, 
    Filter = Path.GetFileName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) 
}; 

this.fileSystemWatcher.Changed += this.ConfigChanged; 
this.fileSystemWatcher.EnableRaisingEvents = true; 

public void ConfigChanged(object sender, FileSystemEventArgs e) 
{ 
    try 
    { 
     this.fileSystemWatcher.EnableRaisingEvents = false; 
     s_logger.Info("Configuration file changed."); 
     // reload config here 
     s_logger.Info("Configuration settings reloaded."); 
    } 
    catch (Exception exception) 
    { 
     s_logger.Error(exception.Message); 
     s_logger.Error("Failed to reload configuration settings."); 
    } 
    finally 
    { 
     this.fileSystemWatcher.EnableRaisingEvents = true; 
    } 
} 
+0

是的,這個作品完美。它不會重複使用這種方法..很好。謝謝。 – user726720

1

的FileSystemWatcher的可能會引發多個事件的一個文件的變化,檢查出來:

常見的文件系統操作可能會引發多個事件。例如,當文件從一個目錄移動到另一個目錄時,可能會引發幾個OnChanged和一些OnCreated和OnDeleted事件。移動文件是一項複雜的操作,由多個簡單操作組成,因此引發多個事件。同樣,某些應用程序(例如防病毒軟件)可能會導致由FileSystemWatcher檢測到的其他文件系統事件。

FileSystemWatcher Class in MSDN

+0

是的,我已經用我的觀察者編輯了上面的內容。所以請檢查我的手錶是否正常。 – user726720