4

FileSystemWatcher用来检测.docx文件。打开时会检测到文件,但文件名总是“损坏”。

3个例子:

  1. 如果我的文件名是:2711111.docx,则接收的文件名FileSystemWatcher.Changed是:~$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)  {...}

帮助将不胜感激:) 谢谢!

4

3 回答 3

5

这是为 Microsoft Word 设计的。当用户打开文档时,它会创建一个隐藏文件。该文件记录了用户名,因此当其他人试图打开同一个文档时,他们会收到一条体面的消息,告诉他们当前哪个用户打开了该文档进行编辑。

该隐藏文件的文件名是原始文件名,前两个字符替换为~$

使用 Explorer 查看目录时,您通常不会看到此文件,因为它启用了 FileAttributes.Hidden 属性。当然,您也想忽略这些文件,请使用 FileInfo.Attributes 属性来过滤它们。

于 2012-06-24T10:42:15.967 回答
4

订阅更多事件,例如重命名,并输出它们的文件名。

我怀疑您看到的是临时文件名,这些文件名通过重命名更改为实际文件名。

于 2012-06-24T10:26:22.240 回答
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
}

如果您没有获得所需的文件,您可以订阅另一个事件,即重命名事件。

于 2012-06-24T10:33:37.633 回答