当文件被更改但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)
{
}
}
对于初学者来说,您滥用了FileSystemWatcher
,因为它是一个一次性组件——它应该存储在字段中,而不是本地变量,并在不再需要时进行处理。
因为您没有存储长期引用,所以可能会被垃圾收集,而则可能会导致调试停止。
此外,它可能会多次启动,这取决于与文件交互的其他程序对文件执行的操作,并且不能保证在收到通知时您的程序可以访问该文件。
正如评论中所回避的那样,你真的需要a)实现你的TODO,或者b)删除这些空的catch
块(更好的选择,IMO)。你说"没有例外",但你现在很难发现。最好是让程序崩溃并出现一个丑陋的错误。