Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileSystemWatcher distorts filename

I'm using FileSystemWatcher to detect .docx files. Files are detected when open, however the filename is always "corrupted".

3 examples :

  1. If my file name is : 2711111.docx, the file name recived in FileSystemWatcher.Changed is : ~$711111.docx.

  2. For file : *2711111_1.docx* I get the filename : *~$11111_1.docx* I can't guess what my filename will be, so I am looking for a general solution.

  3. For file contains/starts with a letter, it doesn't happen.

Here's my code

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)  {...}

Help will be much appreciated :) Thanks!

like image 929
dusm Avatar asked Dec 26 '22 22:12

dusm


2 Answers

This is by design for Microsoft Word. It creates a hidden file when a user opens a document. That file records the user name so that when somebody else tries to open the same document, they'll get a decent message that tells them what user currently has the document opened for editing.

The file name of that hidden file is the original file name with the first two characters replaced with ~$

You don't normally see this file when looking at the directory with Explorer because it has the FileAttributes.Hidden attribute turned on. Surely you want to ignore these files as well, use the FileInfo.Attributes property to filter them.

like image 99
Hans Passant Avatar answered Jan 09 '23 09:01

Hans Passant


Subscribe to a few more events, such as renaming, and output their filenames.

I suspect what you're seeing are temporary filenames which get changed to the actual filename with a rename.

like image 31
CodesInChaos Avatar answered Jan 09 '23 10:01

CodesInChaos