我想使用文件系统观察程序并在文件更改时在表单上显示更改的信息但触发了事件但是它被触发了两次而不是一次,我想要显示的表单从未显示过程序停止而不显示任何异常,它只是停止调试
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)
{
}
}
答案 0 :(得分:3)
对于初学者来说,你误用了FileSystemWatcher
,因为它是一次性组件 - 它应该存储在一个字段中,而不是一个局部变量中,并在不再需要时进行处理。
因为你没有存储长期存在的引用,所以可能被垃圾收集,并且可能导致调试停止。
此外,它可能会多次触发,具体取决于文件与文件交互时对文件执行的操作 - 并且无法保证 可以访问该文件您收到通知时的程序。
正如评论中所提到的,你真的需要a)实现你的TODO,或者b)删除这些空的catch
块(更好的选项,IMO)。你说“没有异常被抛出”,但你现在很难发现它。让程序崩溃并带来一个丑陋的错误会好得多。