![](/img/trans.png)
[英]How do I close a filestream after it creates a file C# .NET and not use it as a process
[英]How to identify and close a process running on a file c# .net
我有一個WCF服務,為WPF客戶端提供pdf。 客戶端在新的WPF窗口中打開pdf並將其顯示在WebBrowser元素中。 服務將pdf作為內存流返回,並且客戶端顯示窗口將內存流復制到文件流。 我希望能夠關閉顯示窗口並使用其他選定的pdf打開一個新窗口。 返回第一個pdf后,我無法再打開一個新的pdf,因為原始pdf文件已附加到流程中。 我無法刪除先前的文件並用新文件替換它,因為它已附加到進程中。 我嘗試在文件filestream.dispose
, filestream.close
上使用filestream.dispose
和filestream.close
方法,並在服務實例上嘗試使用close
方法。 無論我嘗試了什么,我總是會遇到同樣的異常。 該文件將附加到進程。 我什至不知道如何識別仍附加到文件的進程。 我正在使用Visual Studio 2017
客戶端代碼
public void DisplayCard(string SPID, string strAssetDirectory)
{
ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
Stream ms = proxy.GetServiceCard(SPID, strAssetDirectory);
try
{
using (file = new FileStream(Properties.Settings.Default.ServiceCardDisplayPath, FileMode.Create, FileAccess.Write))
{
ms.CopyTo(file);
file.Close();
}
ms.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
proxy.Close();
ServiceCardBrowser.Navigate($"file://{Properties.Settings.Default.ServiceCardDisplayPath}");
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
File.Delete(Properties.Settings.Default.ServiceCardDisplayPath);
//file.Close();
file.Dispose();
this.Owner.Focus();
}
有沒有辦法確定附加到文件的進程?
您的代碼需要在幾個地方進行改進
將using
塊用於Stream
和FileStream
。
您無需將文件對象保留為成員變量。 即使是您嘗試再次處理的已處理文件流。 在編碼方面有關注的隔離。 將文件寫入本地目錄后,即可完成DisplayCard
作用域。 讓ServiceCardBrowser
處理應該如何在指定的文件路徑上進行操作。
public void DisplayCard(string SPID, string strAssetDirectory) { using (ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client()) { using (Stream ms = proxy.GetServiceCard(SPID, strAssetDirectory)) { try { using (file = new FileStream(Properties.Settings.Default.ServiceCardDisplayPath, FileMode.Create, FileAccess.Write)) { ms.CopyTo(file); file.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } ServiceCardBrowser.Navigate( $"file://{Properties.Settings.Default.ServiceCardDisplayPath}"); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { File.Delete(Properties.Settings.Default.ServiceCardDisplayPath); this.Owner.Focus(); }
file.dispose
已被刪除,因為它已經被DisplayCard
。 現在在Window_Closing
,您應該檢查如何將瀏覽器源設置為null。 如果ServiceCardBrowser
是控件,則可以將其設置為
ServiceCardBrowser.Source = null;
或包裝器,然后檢查如何重置源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.