In my code, I have read and write in .csv file.
using (StreamWriter file = new StreamWriter(destFile, true))
{
string[] lines;
file.WriteLine("Date,Entity, ProdFamily);
for (int i = 0; i < numberFile; i++)
{
Console.WriteLine(files[i]);
lines = System.IO.File.ReadAllLines(files[i]);
foreach (string line in lines)
{
if (line != lines[0])
{
file.WriteLine(string.Format("{0},{1},{2},
values[43], values[0], values[3]);
}
}
}
}
After that, I write the code to sort
the contain of the file.
var sorted =
File.ReadLines(destFile)
.Select(line => new {
SortKey = Int32.Parse(line.Split(',')[4]),
Line = line
})
.OrderBy(x => x.SortKey)
.Select(x => x.Line);
File.WriteAllLines(destFile, sorted);
However, the error shown saying that I still did not close
my file. It says that the process cannot access the file because it is being used by another process.
Exception thrown: 'System.IO.IOException' in mscorlib.dll
I try use using
to ensure that the file is closed automatically but the error is still exist.
The code contained in the using
is irrelevant here, and is closing the file correctly, the second block of code is at fault - enumerating the result of File.ReadLines()
has opened the file for reading, and will not close it until the enumerator is closed. As a result, you can’t write to the same file while the enumeration is in progress.
Your options would seem to be either to write to a different file in your File.WriteAllLines()
from the one you’re reading in File.ReadLines()
, or you could ensure the enumeration is complete before writing the sorted data by adding a .ToList()
after the last .Select(...)
used to initialize sorted
, or you could read all the lines in one go (so that the file is closed again before trying to write to it), by using File.ReadAllLines()
instead of File.ReadLines()
.