为什么FileSystemWatcher不会触发事件,而是使用SMSTrace?

时间:2014-07-23 05:10:16

标签: c# .net

我创建了一个FileSystemWatcher对象来监视日志文件。它被初始化为侦听所有可能的事件(lastwrite,lastaccess等等),但是在写入文件时它不会触发事件。

但是,如果我打开SMSTrace并用它来监听该文件(并清楚地看到文件不断更新),filesystemwatcher就会触发事件。 SMSTrace对文件做了什么? 如何解释这个问题以及如何解决?

这是代码:

    private FileSystemWatcher fileWatcher;
    private FileStream fileStream;
    private StreamReader streamReader;
    private String fullPath = null;
    private String dir = null;
    private String fileName = null;

    private void selectLogFile()
    {
        // TODO: try to restore previous settings before asking the user for the log file
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.InitialDirectory = "C:\\";
        openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 2;
        openFileDialog.RestoreDirectory = true;

        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            fullPath = openFileDialog.FileName;
            dir = Path.GetDirectoryName(fullPath);
            fileName = Path.GetFileName(fullPath);
        }
    }


    // TODO: what to do when file erases? (reboot) - clear the window?
    public LogListener()
    {
        try
        {
            Thread selectFileThread = new Thread(new ThreadStart(selectLogFile));
            selectFileThread.SetApartmentState(ApartmentState.STA);
            selectFileThread.Start();
            selectFileThread.Join();

            // The user did not select a file - nothing to do
            if (fullPath == null)
            {  
                return;
            }

            // Create file listener to listen on changes to log
            fileWatcher = new FileSystemWatcher(dir);

            // Create a file stream to read the data from the log file
            fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            // Create a stream reader from the fileStream to read text easily
            streamReader = new StreamReader(fileStream);

            // Watch for changes in LastWrite 
            fileWatcher.NotifyFilter = NotifyFilters.LastWrite;

            // Only watch the log file.
            fileWatcher.Filter = fileName;

            // Add event handlers.
            fileWatcher.Changed += new FileSystemEventHandler(OnChanged);

            // Initial syncing of the file
            readFile();

            // Begin watching for events
            fileWatcher.EnableRaisingEvents = true;

            Log.Add("Started");
        }
        catch (Exception e)
        {
            Log.Add("Exception: " + e.Message);
        }
    }

    void OnChanged(object source, FileSystemEventArgs e)
    {
        readFile();
    }

    public void readFile()
    {
        String line;
        String bytesString = "";
        Log.Add(DateTime.Now+":readFile()...");

        // Some more code here...
    }

2 个答案:

答案 0 :(得分:0)

这是一个很长的镜头,因为你没有提供任何代码,但是......

您是否记得在FileSystemWatcher上将EnableRaisingEvents属性设置为true? e.g:

var w = new FileSystemWatcher("path");
w.Created += DoSomething;
w.Changed += DoSomething;
w.EnableRaisingEvents = true; // No events raised until you do this!
编辑:好的,你已经这样做了。请忽略这个答案,我不知道发生了什么:P

答案 1 :(得分:0)

要查找的内容是删除代码,然后在创建flesystemwatcher后重新添加您正在观看的文件夹。如果它这样做,则观察者变得无效,并且您不会获得任何事件。 我今天的代码中有一个错误就是这样做了,并在阅读完这篇文章后想出来了。