进程无法访问该文件,因为另一个进程ioexception正在使用该文件



不太清楚为什么我已经使用了usingfs.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();

最新更新