Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program crashes after trying to use a recently created file. C#

So here is my code

if (!File.Exists(pathName))
{
    File.Create(pathName);
}
StreamWriter outputFile = new StreamWriter(pathName,true);

But whenever I run the program the first time the path with file gets created. However once I get to the StreamWriter line my program crashes because it says my fie is in use by another process. Is there something I'm missing between the File.Create and the StreamWriter statements?

like image 368
Jason T. Avatar asked Dec 13 '25 07:12

Jason T.


2 Answers

File.Create doesn't just create the file -- it also opens it for reading and writing. So the file is indeed already in use when you try to create the StreamWriter: by your own process.

StreamWriter will create the file specified by pathName if it doesn't exist, so you can simply remove the File.Exists check and simplify your your code this:

using (var writer = new StreamWriter(pathName, true))
{
   // ...
}

From MSDN:

StreamWriter Constructor (Stream)

Initializes a new instance of the StreamWriter class for the specified file [...]. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

like image 150
dtb Avatar answered Dec 14 '25 20:12

dtb


As others have mentioned, File.Create is creating a FileWriter that's holding your file open. But aside from that, there's no reason to check for file existence before trying to open the file. Just tell File.Open to open an existing file if one is there:

var outputFile = new StreamWriter(File.Open(pathName, FileMode.OpenOrCreate));
like image 30
JSBձոգչ Avatar answered Dec 14 '25 20:12

JSBձոգչ