简体   繁体   中英

StreamWriter, FileStream and windows file locks

I am writting a small app to export and import data from database using .NET DataSets and XML and as part of that I am doing the following.

StreamWriter sw = new StreamWriter(file);
sw.Write(xml.OuterXml);
sw.Close();

The problem is that the close method closes the FileStream (file parameter passed to constructor) but doesn't release the file lock. The file is one that the program I have written creates so I know nothing else is locking it.

Is there something I am doing wrong or is this a windows bug?

EDIT

Yes 'file' is a FileStream object and I naively assumed that calling close() on the stream that wraps the files stream would also cleanup and dispose the underlying file stream by calling the FileStream.close method. But i'm not sure about that any more.

Wrapping this in a using block still has the same effect.

One extra note is that the filestream object is created in a different method but that shouldn't make any difference

Try using this instead:

using (StreamWriter sw = new StreamWriter(file))
  sw.Write(xml.OuterXml);

(or try to call sw.Dispose() manually)

Would it help to wrap the file stream in a using or simply use the overloaded method for creating the stream writer:

using (FileStream fs = new FileStream("path", FileMode.Append))
using (StreamWriter sw = new StreamWriter(fs))
{
    sw.Write(xml.OuterXml);
    sw.Close();
}

or:

using (StreamWriter sw = new StreamWriter("path"))
{
    sw.Write(xml.OuterXml);
    sw.Close();
}

I suspect the problem is in the code creating or using the FileStream. Perhaps you could elaborate on how you use the FileStream object you create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM