我有一个视图,该视图用于显示PDF文档作为程序的一部分。的代码在这里:
<Grid>
<WebBrowser local:HelpWebBrowser.BindableSource="{Binding PdfBrowserSource}" Name="Test" Grid.Row="0" Grid.Column="0" Visibility="{Binding PdfBrowserVisibility}"/>
<TextBox Text="Sorry,unable to load help page. Please check your internet connection to Sage." Grid.Row="0" Grid.Column="0" FontSize="26" TextWrapping="Wrap" Padding="20"/>
</Grid>
BindableSource是在in this answer中找到的代码,此外,我还有一个ViewModel来处理获取并保存文件:
private string pdfBrowserSource;
public string PdfBrowserSource
{
get { return pdfBrowserSource; }
set { pdfBrowserSource = value; OnPropertyChanged(nameof(PdfBrowserSource)); }
}
public HelpViewModel() : base("Help")
{
string filepath = GetPDFFilePath();
if (!string.IsnullOrEmpty(filepath)) {
PdfBrowserSource = filepath;
PdfBrowserVisibility = Visibility.Visible;
} else
{
PdfBrowserSource = null;
PdfBrowserVisibility = Visibility.Hidden;
}
}
private string GetPDFFilePath()
{
// Code to get hash of PDF from database - removed
return CreateFileFromHash(result.FLData.ToArray());
}
private string CreateFileFromHash(byte[] file)
{
Console.WriteLine("CreateFileFromHash()");
string filepath = Path.GetTempPath() + "HelpFile.pdf"
File.WriteAllBytes(filepath,file);
return filepath;
}
这在我第一次打开帮助窗口时有效,PDF会按预期显示。但是,在随后的打开中,该文件被认为仍在使用中,因此无法打开以进行显示。即使访问该文件的原始窗口已关闭,也会在File.WriteAllBytes(filepath,file);
处引发异常。
我尝试了OnClosing事件来删除文件,但是这里出现了同样的错误。我还尝试通过在文件名中使用随机字符串来创建单独的文件。但是,这会抛出一个单独的错误,但仍在同一行。
我无法弄清楚文件的存放位置以及如何释放文件以使其再次打开?
错误消息:
System.IO.IOException:该进程无法访问文件'C:\ Users \ MY_username \ AppData \ Local \ Temp \ HelpFile.pdf',因为该文件正在被另一个进程使用。
文件名中包含随机字符串的错误消息:
System.IO.IOException:进程无法访问文件'C:\ Users \ harry.adams \ AppData \ Local \ Temp \ System.Linq.Enumerable + WhereSelectEnumerableIterator`2 [System.String,System.Char]。 pdf”,因为它正在被另一个进程使用。
随机文件名处理:
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string filepath = Path.GetTempPath() + Enumerable.Repeat(chars,10).Select(s => s[random.Next(s.Length)]).ToString() + ".pdf";