该进程无法访问文件 yyyy,因为它正被另一个进程使用

The process cannot access the file yyyy because it is being used by another process

我将文件存储在 SQL 服务器数据库中,如果用户 select 我也会在我的应用程序中显示这些文件。这就是我所做的:

LetterBAL letterBal = new LetterBAL();
string filter = "Id=" + letterListView.SelectedItems[0].Text;

Letter letter = letterBal.GetLetterImage(filter);        

string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = path + "\IssuedLetter\" +letter.Id.ToString() + "." +letter.FileExt;                

webBrowser1.Navigate(path);


public Letter GetLetterImage(string filter)
{
      LetterDB letterDB = new LetterDB();
      Letter letter = letterDB.GetLetterImage(filter);

      string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      path = path + "\IssuedLetter";
      path = path + "\" + letter.Id.ToString() + "." + letter.FileExt;               

      using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
      fs.Write(letter.ltr_Image, 0, letter.ltr_Image.Length);           
      return letter;
}

用户第一次 select 文件时,它在网络浏览器中显示没有问题。但是如果第二次(当网络浏览器仍然显示相同的 pdf 文件时)它说

The process cannot access the file 'C:\Users\mj.PG\Documents\IssuedLetter.PDF' because it is being used by another process.

用户再次点击同一个文件查看,如何处理?

有几种方法可以避免阻塞:

  1. 完全不使用中间文件,使用WebBrowser的DocumentStream 属性和MemoryStream作为源。
  2. 为每封信使用新的临时文件名。不要忘记应用程序关闭时的清理程序。
  3. 最灵活且更耗时的方法是在您的应用程序中嵌入一个小型 http 服务器,例如基于 OWIN self-hosting 组件。因此,您还可以构建具有身份验证、授权和其他功能的基于 html 的现代用户界面。作为奖励,您的应用程序可以从本地网络中的其他计算机访问并轻松实现 Windows 服务,如果您愿意的话。