Tutorial :Dataset ReadXML method Stream vs. String



Question:

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?


Solution:1

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.


Solution:2

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


Solution:3

"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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »