You do not need to create the file before using
WriteAllLines
.
It is possible you run into a race condition by using
WriteAllLines
just after
Create
.
You could try:
if (!File.Exists(filePath))
{
List<string> output = new List<string>();
output.Add($"{Person.name},{Person.carName},{Person.carMaxSpeed},{Person.coins}");
File.WriteAllLines(filePath, output);
}
[Edit] Some more precisions:
Usually, you use
File.Create
when you want to get a
FileStream
object (which is the return type of the
Create
method) that you reuse later in your code. When you do so, it is a good idea to use it in a
using
block, so that system resources are properly disposed at the end.
using (FileStream stream = File.Create(...))
{
}
Whereas
File.WriteAllLines
does not return anything, it just opens or creates the file, writes to it, and then closes it.
Hope this makes sense.