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

the process cannot access the file because it is being used by another process 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 'if the target file already exists, it is overwritten'.

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();