Mike_G
Mike_G

Reputation: 16502

Writing to a file in Asp.Net

I am trying to write to a file in a Asp.Net form (.aspx). I can create the file fine using,

  if (!File.Exists(Settings.Default.FileLocation))
     {
       File.Create(Settings.Default.FileLocation);
     }

But when I go to write to the file using this code:

File.WriteAllBytes(Settings.Default.FileLocation, someByteArray);

I get an exception:

System.IO.IOException: The process cannot access the file 'C:\inetpub\wwwroot\mysite.com\captured\captured.xml' because it is being used by another process.

(in this case 'C:\inetpub\wwwroot\mysite.com\captured\captured.xml' == Settings.Default.FileLocation)

I cant delete or copy the file in Windows Explorer during this time as well. However, if I stop or restart the Application Pool the WebForm is running in, the error goes away. What is the cause of this and how do I prevent it?

This is running on a Win server 2012 R2 and IIS 7.5

Upvotes: 0

Views: 105

Answers (2)

John Koerner
John Koerner

Reputation: 38077

File.Create opens the file for read/write by default and needs to be closed before it can be used again. From the docs:

By default, full read/write access to new files is granted to all users. The file is opened with read/write access and must be closed before it can be opened by another application.

File.WriteAllBytes will create the file if it doesn't exist, so I think your code to check for file existence and creating it is probably overkill.

Upvotes: 1

mason
mason

Reputation: 32694

Read the documentation on MSDN. You should be using using statements to open the file so that you can make sure any open handles to it are closed.

using(FileStream fs=File.Create(Settings.Default.FileLocation))
{
    //manipulate file here
}

Also, File.WriteAllBytes will create the file if it doesn't exist, so there's no need to separately create it.

Upvotes: 6

Related Questions