tags:

views:

43

answers:

3

I am trying to create a new file and write XML to it:

FileStream output = File.Create(Path.Combine(PATH_TO_DATA_DIR, fileName));

The argument evaluates to:

C:\path\to\Data\test.xml

The exception is:

The process cannot access the file 'C:\path\to\Data\test.xml' because it is being used by another process.

What am I doing wrong here?

UPDATE: This code throws the same exception:

StreamWriter writer = new StreamWriter(Path.Combine(PATH_TO_DATA_DIR, fileName));

UPDATE 2: The file I am trying to create does not exist in the file system. So how can be it in use?

UPDATE 3: Changed to a new file name, and now it works. I'm not sure why. Perhaps I unknowing created it in the first call, and it failed on subsequent calls?

A: 

Your program keeps a handle on your file after it's being created to return to your FileStream object. Because you don't specify the access to it, perhaps it won't let you get a grab on it. Perhaps should you consider closing it, and then reopen it in a proper manner by specifying how you want it open (ReadOnly, ReadWrite, WriteOnly) ?

Will Marcouiller
I can't close it, because `File.Create()` is throwing an exception. Neither the handle nor the file exists prior to that call.
Rosarch
Then it sounds like you're trying to create a file which already exists.
Will Marcouiller
A: 

The message means that another process is using that file. If you have it open it could be using it, or when it was originally created if the stream was not closed properly that could do it also.

First check to make sure you do not have it open. I would try to change the fileName and see if you get the same error. If you do get the same error than some place in your code it is not closing a stream that when it is done with the file.

David Basarab
As I clarified above, the file does not exist in the file system before this code runs. So how can another process be using it?
Rosarch
That is what I meant within my answer. Thanks David Basarab to have made it clearer. =)
Will Marcouiller
A: 

Not trying to sound insulting, but does the folder exist? Does the file already exist but is hidden by the system? And does the user account that is running the program have write permissions to the folder? Have you tried creating a file using a different method (like with File.WriteAllText(<path>, "Testing") just to see if it's your particular call to File.Create?

CuppM