首页 > 解决方案 > 仅当使用 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 包。

标签: c#nugetfilesystemwatcher

解决方案


推荐阅读