when I try to use the following code in the codebehind file, it runs successfully but when I refresh the ASP.NET webform it gives an error of file already in use, the error is given below the code.
string filename = "D:\\project\\data\\latest\\today.xml";
XmlSerializer serializer = new XmlSerializer(typeof(searchResult));
serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);
FileStream fs = new FileStream(filename, FileMode.Open);
searchResult po;
po = (searchResult)serializer.Deserialize(fs);
Here is the error
The process cannot access the file ‘D:\project\data\latest\today.xml’ because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: The process cannot access the file ‘D:\project\data\latest\today.xml’ because it is being used by another process.
Error Source
Line 141: FileStream fs = new FileStream(filename, FileMode.Open);
Every time you use a stream to open a file there’s a chance that you lock the file so that no other stream can reach the file.You should close your streams as fast as possible.
I’d prefer to use the using keyword every time I am working with an IDisposable object.
I mean :
in this manner even if I forget to close my stream it will be disposed finally and will be closed anyway.