The process cannot access the file when using StreamWriter

Basically I want to create a file if it does not exist, and then write a 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.

+5
source share
3 answers

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

Since you did not select it, the file remains locked, and subsequent accesses to the file will fail due to this situation if they are executed from other descriptors (i.e., other FileStreamor integer StreamWriter).

, IDisposable, FileStream:

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

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

    }
}
+14

StreamWriter, ?

StreamWriter sr = new StreamWriter(filePath + fileName);

MSDN:

path , (UNC). , ; .

, Path.Combine .

+3

Simplify your code using one 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.

+2
source

All Articles