views:

79

answers:

4

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?

+1  A: 

After the File.Create the stream is still open.

You could use:

File.Create(pathName).Close();

This creates the file and closes it directly.

More accepted is:

using (var file = File.Create(pathName)) {
   // use the file here
   // it will be closed when leaving the using block
}

Also: Why do you create a file, that you create 2 lines further in your code? The StreamWriter constructor (with append=true) will create or append the file if it does not exist.

GvS
Good question. And the answer is I don't know. I'm still new to C# and this is my experimentation program that I'm playing with.
Jason T.
+6  A: 

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.

dtb
Even that is too much, isn't it? He can just use a writer with the filename and a boolean to open for appending.
Anthony Pegram
Easier to just create the `StreamWriter` with `new StreamWriter(pathName, true)`. That will create the file if it doesn't exist and append to it if it does. (Edit: I see @Anthony said the same thing :) ).
Jeff Yates
Indeed... Fixed!
dtb
A: 

File.Create returns a FileStream. Why don't you save that and pass it to the StreamWriter constructor instead of passing a pathname?

KrisTrip
+2  A: 

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));
JSBangs
This doesn't open the file for appending, right?
dtb
Good point about checking for existance. Not only pointless, it can actually make the application vulnarable to [race conditions](http://en.wikipedia.org/wiki/Race_condition).
Patrick