不确定为什么我已经使用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();
}
答案 0 :(得分:0)
可能您的文件仍然被锁定。 fs.close或using语句不会立即释放文件,这可能需要一些时间。
我了解到您下次要读取该文件,也就是在您收到错误消息后才开始读取。因此,在下次读取文件之前,您可以尝试:
while (true)
{
try
{
read this file from this place
break;
}
catch
{
Sleep(100);
}
}
这不是完美的解决方案,但是您可以以此来验证正在发生的事情,并更加接近解决方案。
fs.close()和file.close()是不必要的,因为using语句会为您关闭此文件。
答案 1 :(得分:0)
我认为问题出在其他地方(您可能在单独的编辑器中打开了文件)。
尽管如此,我还是建议在这种情况下使用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);
答案 2 :(得分:0)
我意识到我已经在原始代码之后附加了文件:
Attachment attachment;
attachment = new Attachment(filePath);
因此,我的解决方法是将其处置,然后错误消失了。
attachment.Dispose();