Search code examples
c#filestreamstreamwriter

the process cannot access the file because it is being used by another process ioexception


Not so sure why I have already use using and fs.Close() and file.Close() but I am still getting this error the second time I run these code.

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

Solution

  • I realize I have attached the file after my original code:

     Attachment attachment;
     attachment = new Attachment(filePath);
    

    So, my fixes is to dispose it, then the error is gone.

    attachment.Dispose();