user1108948
user1108948

Reputation:

The process cannot access the file when using StreamWriter

Basically I want to create a file if not existing then write message to it.

if (!File.Exists(filePath + fileName))
    File.Create(filePath + fileName);
StreamWriter sr = new StreamWriter(filePath + fileName,false);

How to deal with this error?

The process cannot access the file 'c:\blahblah' because it is being used by another process.

Upvotes: 8

Views: 27690

Answers (3)

Daniel Kelley
Daniel Kelley

Reputation: 7737

Why not just use the StreamWriter constructor that takes in the file name?

StreamWriter sr = new StreamWriter(filePath + fileName);

From MSDN:

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. If the file exists, it is overwritten; otherwise, a new file is created.

Very minor point but you could consider using Path.Combine when concatenating file names and folder paths.

Upvotes: 4

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

File.Create opens a FileStream (http://msdn.microsoft.com/en-us/library/d62kzs03.aspx).

As you didn't dispose it, the file remains locked and subsequent accesses to the file will fail because of this situation if these are performed from other handles (i.e. other FileStream or the whole StreamWriter).

This code demonstrates how you should work with IDisposable objects like FileStream:

if (!File.Exists(filePath + fileName))
{
    File.Create(filePath + fileName).Dispose();

    using(StreamWriter sr = new StreamWriter(filePath + fileName,false))
    {

    }
}

Upvotes: 24

sll
sll

Reputation: 62484

Simplify your code by using single method to create and open a file:

using (FileStream fs = File.OpenWrite(path)) 
{
    Byte[] info = new UTF8Encoding(true)
                         .GetBytes("This is to test the OpenWrite method.");

    fs.Write(info, 0, info.Length);
}

MSDN: (File.OpenWrite Method)

Opens an existing file or creates a new file for writing.

Upvotes: 3

Related Questions