c# - 仅当使用 nuget 包时,文件才被另一个进程使用
问题描述
今天出现了一个奇怪的问题。我正在设置一个 FileSystemWatcher。一旦文件夹中发生写入更改(文件夹中只有 1 个文件),我打开文件并读取 xml 条目。我将读取的代码打包到一个单独的 nuget 中,因为我在多个项目中使用它。要触发问题,我在记事本中打开 xml 文件,对其进行编辑并保存。这是负责读取 xml 的代码:
public bool GetBoolean(string value)
{
using (FileStream fileStream = File.Open(this.confFile, FileMode.Open, FileAccess.Read))
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load((Stream) fileStream);
XmlNode xmlNode = xmlDocument.DocumentElement.SelectSingleNode("/path/" + value);
return Convert.ToBoolean(xmlNode.InnerText);
}
}
这是更改监听代码:
void StartListeningForChanges(){
void OnChanged(object source, FileSystemEventArgs e){
Console.WriteLine("{0}, with path {1} has been {2}", e.Name, e.FullPath, e.ChangeType);
bool whatisit= Someclass.GetBoolean("someentry");
}
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.IncludeSubdirectories = false;
watcher.Path = confFolder;
watcher.Filter = "*.*";
watcher.Changed += OnChanged;
watcher.EnableRaisingEvents = true;
}
如果 OnChanged 使用 nuget 包中的代码,我会收到一条错误消息"The process cannot access the file because it is being used by another process"
。如果我使用相同的代码,但只是将其直接粘贴到项目中:
void StartListeningForChanges(){
void OnChanged(object source, FileSystemEventArgs e){
Console.WriteLine("{0}, with path {1} has been {2}", e.Name, e.FullPath, e.ChangeType);
using (FileStream fileStream = File.Open(this.confFile, FileMode.Open, FileAccess.Read))
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load((Stream) fileStream);
XmlNode xmlNode = xmlDocument.DocumentElement.SelectSingleNode("/fullpath");
// do something with xmlNode.InnerText
}
}
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.IncludeSubdirectories = false;
watcher.Path = confFolder;
watcher.Filter = "*.*";
watcher.Changed += OnChanged;
watcher.EnableRaisingEvents = true;
}
比没有抛出错误,就好像该项目正在使用未使用只读流的先前版本的 nuget 包。IDE 确实显示了正确的版本。
可能是什么问题呢?由于未来的更新,我想继续使用 nuget 包。
解决方案
推荐阅读
- reactjs - 无法在本机基础中打开抽屉
- grpc - 如何使用nest.js创建不在控制器中的grpc客户端
- sql - 重复项的 SQL 结果 - Oracle
- python - VTK,Mayavi BUG:所有 `ButtonReleaseEvents` 都失败,但所有 `ButtonPressEvents` 工作?
- ruby-on-rails - 未执行索引控制器操作且未呈现视图
- agda - 编码集合(唯一元素列表)的正确方法是什么?
- java - 在 React Native 的桥接 Java 方法中使用 Logback
- ruby-on-rails - DotEnv 不会在 database.yml 中加载值
- office-js - 如果在几分钟后等待,则无法在 ItemSend 事件中关闭 Dialog API 对话框
- nuxt.js - 如何开始将 AWS Amplify 集成到 Nuxt.js 项目?