views:

83

answers:

3

I have code that calls the ReadXml method of the DataSet class and passes in a file name ReadXml(strFileName). Occasionally this throws a System.IO.IOException because the file is being used by another process.

If I change the code to use the ReadXml(stream) method and pass in a FileStream like this:

using(FileStream fs = new FileStream(this.filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ))
{
     MyDS.ReadXxml(FileStream);
}

Will that prevent the IOException from occuring? What is going on under the hood when you simply pass in a file name?

A: 

Most likely, they both open a FileStream and pass it to XmlReader.Create, then use the XmlReader to process the data.

John Saunders
If you dive deep enough into the framework code it calls: new FileStream(uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 1);
Mikael Svenson
@Mikael: is the FileStream ever passed to XmlReader.Create?
John Saunders
@John: Actually it uses new XmlTextReader(string url)
Mikael Svenson
@Mikael: i looked that up last night and saw the same thing. Developers: "don't try this at home". new XmlTextReader()" has been deprecated since .NET 2.0
John Saunders
A: 

"Occasionally this throws a System.IO.IOException because the file is being used by another process."

As you said, it's throwing an Exception because the file is being used by another process. Nothing you can do about that - stop the other process from using the file and it will work again.

If you believe this is false, then you should check that all your FileStreams are correctly closed, using the using construct as you are in the question.

Hope that helps.

Kieren Johnstone
A: 

The DataSet class will create a FileStream object for you if you pass in the filename as a string. The overloaded method that takes a Stream as a parameter allows you to pass in a Stream object if you have one instead of a filename.

The version that takes a string as a parameter will simply create a FileStream and pass that onto the version that takes a Stream as a parameter.

You should use the overload that suits the data you have. In this case the string.

Philip Smith