2012-06-24 41 views
4

我使用FileSystemWatcher來檢測.docx文件。文件在打開時被檢測到,但文件名總是「損壞」。FileSystemWatcher扭曲文件名

3個例子:

  1. 如果我的文件名:2711111.docx,在FileSystemWatcher.Changed recived文件名是:〜$ 711111.docx

  2. 對於文件:* 2711111_1.docx *我得到的文件名:*〜$ 11111_1.docx * 我無法猜測我的文件名是什麼,所以我正在尋找一個通用的解決方案。

  3. 對於文件包含/開頭的字母,它不會發生。

這裏是我的代碼

MyPath = String.Format(@"C:\Users\{0}\NRPortbl\ACTIVE\{1}\"", 
     Public.UserName, Public.UserName); 

FileSystemWatcher watcher = new FileSystemWatcher(); 
if (!System.IO.Directory.Exists(MyPath)) 
{ 
    Public.Logger.Error(
     String.Format 
      ("Path of folders {0} not found", MyPath)); 
    System.Windows.Forms.MessageBox.Show(
     String.Format(
      "There was a problem loading {0} " + 
      "NRPortbl libraray, contact administrator", Public.UserName)); 
    return; 
} 
watcher.Path = MyPath; 
watcher.Filter = "*.Docx";              
watcher.IncludeSubdirectories = false; 
watcher.Changed += new FileSystemEventHandler(OnChanged);      
watcher.Deleted += new FileSystemEventHandler(OnDeleted); 
watcher.EnableRaisingEvents = true; ... 
public void OnChanged(object source, FileSystemEventArgs e) {...} 

幫助將非常感激:)謝謝!

+0

只有一次變得被觸發?或者打開一個docx文件時多次? – nawfal

回答

5

這是爲Microsoft Word設計的。它在用戶打開文檔時創建一個隱藏文件。該文件記錄了用戶名,以便當其他人試圖打開同一文檔時,他們會得到一條體面的消息,告訴他們當前有哪些用戶打開了文檔以進行編輯。

隱藏的文件的文件名是在使用資源管理器的目錄中查找時,因爲它具有FileAttributes.Hidden前兩個字符與~$

你通常不會看到此文件替換原來的文件名屬性開啓。當然你也想忽略這些文件,使用FileInfo.Attributes屬性來過濾它們。

+0

嗨,謝謝你的迴應,如果我定義這個文件夾是隱藏的,那麼每次我打開一個文件,我不會達到「創建」功能,是不是有一種方法來計算出「真實」名稱的檔案?我試着做: System.IO.FileInfo info = new System.IO.FileInfo(MyPath); info.Attributes = FileAttributes.Hidden; – dusm

+0

我對這個評論無能爲力。你當然不想*設置隱藏的屬性,只有* test *它。 –

+0

嗨,只是當我需要文件名時,我用〜$獲得文件名,所以我想「查找」原始文件名,如人眼所示,以便跟蹤它。 – dusm

4

訂閱其他一些事件,如重命名,並輸出文件名。

我懷疑你所看到的是臨時文件名,它們被重命名爲實際文件名。

1

未經測試的代碼,但我記得自己做的伎倆像在此之前..

首先,當你打開文件或保存文件,OnChanged事件(希望)火多次。所以你可以看到,一旦你得到正確的文件名。爲了看到這一點,你可以使用文件存在功能和其他一些技巧。喜歡這個左右:

public void OnChanged(object source, FileSystemEventArgs e) 
{ 
    if (e.FullPath.Contains("~$")) //to avoid the corruption you are talking about. 
     return;     //or better handling - trivial 

    if (!File.Exists(e.FullPath)) //to avoid some temp files that need not be visible 
     return;     //but happens with doc files. 

    //got the file e.FullPath 
} 

如果你沒有得到所需的文件,你可以訂閱另一個事件,重命名事件。