![](/img/trans.png)
[英]IOException: The process cannot access the file because it is being used by another process
[英]the process cannot access the file because it is being used by another process ioexception
不太清楚為什么我已經使用了using
和fs.Close()
和file.Close()
但我第二次運行這些代碼時仍然收到此錯誤。
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
using (StreamWriter file = new StreamWriter(fs))
{
// Display header
string header = string.Format("{0,-40} {1,-12} {2,-15} {3,-8}",
"Product Name", "Unit Price", "Quantity", "Total");
file.WriteLine(header);
foreach (var item in shoppingCart2)
{
file.WriteLine("{0,-40} {1,-12} {2,-15} {3,-8}", item.ProductName,
Utility.FormatAmount(item.UnitPrice), item.QuantityOrder,
Utility.FormatAmount(item.TotalAmount));
table.AddRow(item.ProductName, Utility.FormatAmount(item.UnitPrice),
item.QuantityOrder, Utility.FormatAmount(item.TotalAmount));
}
table.Options.EnableCount = false;
table.Write();
file.Close();
}
fs.Close();
}
可能您的文件仍處於鎖定狀態。 fs.close 或 using 語句不會立即釋放文件,這可能需要一些時間。
我了解您下次想閱讀此文件,而這就是您收到錯誤消息的時候。 因此,在下次讀取文件之前,您可以嘗試:
while (true)
{
try
{
read this file from this place
break;
}
catch
{
Sleep(100);
}
}
這不是完美的解決方案,但您可以通過此驗證正在發生的事情,並更接近解決方案。
fs.close() 和 file.close() 是不必要的,因為 using 語句會為您關閉這些文件。
我認為問題出在其他地方(您可能在單獨的編輯器中打開了文件)。
不過,我建議在這種情況下使用WriteAllLines
。 它將最小化文件打開的時間。
請注意,使用WriteAllLines
'如果目標文件已存在,則將其覆蓋' 。
const string template = "{0,-40} {1,-12} {2,-15} {3,-8}";
var lines = new List<string>();
lines.Add(string.Format(template, "Product Name", "Unit Price", "Quantity", "Total"));
foreach (var item in shoppingCart2)
{
lines.Add(string.Format(template, item.ProductName,
Utility.FormatAmount(item.UnitPrice), item.QuantityOrder,
Utility.FormatAmount(item.TotalAmount)));
table.AddRow(item.ProductName, Utility.FormatAmount(item.UnitPrice),
item.QuantityOrder, Utility.FormatAmount(item.TotalAmount));
}
table.Options.EnableCount = false;
table.Write();
File.WriteAllLines(filePath, lines);
我意識到我在原始代碼之后附加了文件:
Attachment attachment;
attachment = new Attachment(filePath);
所以,我的修復是處理它,然后錯誤就消失了。
attachment.Dispose();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.