Here, I create 2 new files, and when I try to File.WriteAllLines()
, it returns an IOException saying that the file is already being used by another process:
Directory.CreateDirectory(tempShiftPath);
File.Create(tempShiftPath "Info.shift");
File.Create(tempShiftPath "Legs.shift");
string[] infoContents =
{
Convert.ToString(shift.TimeFrame.Start) ";" Convert.ToString(shift.TimeFrame.End),
shift.Description
};
File.WriteAllLines(tempShiftPath "Info.shift", infoContents); // Error occures here
return shift;
Things I have tried
I have already read through this question, and I am sure that the "other process" is my process.
I have also added a few seconds of sleep between the creat and the write methods, but that obviously didn't work.
Honestly, I have no idea what is wrong, because it worked some time ago, but now it doesn't.
CodePudding user response:
File.Create
opens a stream to the file. This stream needs to closed, or you will get the error you describe.
However, File.WriteAllLines
creates the file on its own, so there is no need for the File.Create
statement.
This should work just fine:
Directory.CreateDirectory(tempShiftPath);
string[] infoContents =
{
Convert.ToString(shift.TimeFrame.Start) ";" Convert.ToString(shift.TimeFrame.End),
shift.Description
};
File.WriteAllLines(tempShiftPath "Info.shift", infoContents); // No error occurs here
return shift;
File.Create
is meant to be used something like this:
using (FileStream fs = File.Create(path))
{
fs.Write(byteArray, 0, length);
}