0

我想使用文件系统观察程序并在文件更改但触发 onchaged 事件时在表单上显示更改的信息但它被触发两次而不是一次并且我想要显示的表单从不显示并且程序停止而不显示任何异常它都会停止调试

public void Run()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = pathOfPatientFixedFile.Remove(pathOfPatientFixedFile.IndexOf("PatientFixedData.xml")-1);
    watcher.Filter = "PatientFixedData.xml";
    watcher.Changed += new FileSystemEventHandler(watcher_Changed);
    watcher.EnableRaisingEvents = true;
}

private void watcher_Changed(object sender, FileSystemEventArgs e)
{
    try
    {
        GetPatientInfo(e.FullPath);
        frmPatientInfoDisplay displayPatientInfo = new frmPatientInfoDisplay(_patientInfo);
        displayPatientInfo.Show();
    }
    catch (Exception ex)
    {
    }
}

GetPatientInfo 的代码

private void GetPatientInfo(String filePath)
{
    try
    {
        XmlDocument xmlDoc = new XmlDocument();
        using (StreamReader sr = new StreamReader(filePath, Encoding.Default))
        {
            String line = sr.ReadToEnd();
            if (line.IndexOf("<IsPatientFixed>") > 0)
            {
                var value = GetTagValue(line, "<IsPatientFixed>", "</IsPatientFixed>");
                if (value == "true" || value == "True")
                {
                    if (line.IndexOf("<PatientID>") > 0)
                        _patientInfo[0] = GetTagValue(line, "<PatientID>", "</PatientID>");
                    if (line.IndexOf("<PatientName>") > 0)
                        _patientInfo[1] = GetTagValue(line, "<PatientName>", "</PatientName>");
                    if (line.IndexOf("<PatientSex>") > 0)
                        _patientInfo[2] = GetTagValue(line, "<PatientSex>", "</PatientSex>");
                    if (line.IndexOf("<PatientDateOfBirth>") > 0)
                        _patientInfo[3] = GetTagValue(line, "<PatientDateOfBirth>", "<PatientDateOfBirth>");
                }
            }
        }
    }
    catch (Exception ex)
    {
    }
}
4

1 回答 1

3

For starters, you're misusing the FileSystemWatcher since it's a disposable component - it ought to be stored in a field, not a local variable, and disposed when no longer required.

Because you're not storing a long lived reference, it may be being garbage collected, and that may be leading to debugging stopping.

Also, it may fire multiple times, depending on what operations are being performed on the files by whichever other programs are interacting with the file - and there's no guarantee that the file will be accessible to your program at the point at which you receive notification.

As eluded to in the comments, you really need to a) Implement your TODOs, or b) Remove these empty catch blocks (the better option, IMO). You say "no exception is thrown", but you're making that pretty difficult to detect at the moment. It would be far better to let the program crash with a nice ugly error.

于 2012-08-24T07:05:28.460 回答