开发者

FileSystemWatcher() problem when monitoring mapped UNC

开发者 https://www.devze.com 2023-04-03 21:33 出处:网络
I have a problem with the FileSystemWatcher() Class. It works flawlessly when I\'m monitoring a local file on my harddrive. When I change to a mapped UNC, it does not fire anymore. The UNC is mapped t

I have a problem with the FileSystemWatcher() Class. It works flawlessly when I'm monitoring a local file on my harddrive. When I change to a mapped UNC, it does not fire anymore. The UNC is mapped to a local drive (X:), with the NET USE command where the user and password are supplied, this is done in a batch file at startup. Anyone that knows why this doesn't work? I have checked the paths, all of them are correct, so the problem should be related to something else...

fw = new FileSystemWatcher();
        fw.Path开发者_StackOverflow中文版 = fileInfoPath;
        fw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        fw.Filter = fileInfoName;
        fw.Changed += new FileSystemEventHandler(FileOnChanged);
        fw.Created += new FileSystemEventHandler(FileOnChanged);

Help appreciated! :)


My solution to the problem was to leave the FileSystemWatcher() and create my own little watcher. It's very simple, but the only thing I wanted to watch was when the file was rewritten and then perform some action.

This is basically what I do (removed try/catch and some invoking of other threads):

System.Threading.Timer tFileWatcher;
private string fileTime1 = "";
private string fileTime2 = "";
//
private void Form1_Load(object sender, EventArgs e)
    {
        tFileWatcher = new System.Threading.Timer(ComputeBoundOp2, 0, 0, 500);
        fileTime1 = File.GetLastWriteTime(fileInfo).ToFileTime().ToString();
        fileTime2 = File.GetLastWriteTime(fileInfo).ToFileTime().ToString();
    }

private void ComputeBoundOp2(Object state)
    {
        fileTime2 = File.GetLastWriteTime(fileInfo).ToFileTime().ToString();

        if (fileTime1 != fileTime2)
        {
        //Do something
        }
    }


I found a really cool way to get UNC with credentials working with FileSystemWatcher in a windows service on codeproject.

see Adrian Hayes post: http://www.codeproject.com/Articles/43091/Connect-to-a-UNC-Path-with-Credentials

His solution works a treat.


I couldn't get any of the date and time triggers to work. Looking at the file details the server wasn't changing them at all. So instead I used a trigger on the file size (NotifyFilters.Size) which worked a charm. I left the other notifies in just in case I'm not using a UNC.

      fsw.Path = Path.GetDirectoryName(currentFilename);
      fsw.Filter = Path.GetFileName(currentFilename);
      fsw.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size;
      fsw.Changed += new FileSystemEventHandler(fsw_Changed);
      fsw.EnableRaisingEvents = true;  
0

精彩评论

暂无评论...
验证码 换一张
取 消