I want to parse an xml file, serialize data and send it to clients. As you know parsing files may take a bit so i often get the exception:
[IOException: The process cannot access the file 'E:...\file.xml' because it is being used by another process.]
I decided to add a try/catch block to my action controller. If there is an exception, do some thread.sleep and try again. My new code looks like below:
public PartialViewResult _warningsView(string containerId)
{
var myXslTrans = new XslCompiledTransform();
FileStream fileStream = null;
warnings result = null;
bool isFileProcessed = false;
while (!isFileProcessed)
{
try
{
myXslTrans.Load(Properties.Settings.Default.DataFolder + "/alert.xslt");
myXslTrans.Transform(Properties.Settings.Default.DataFolder + "/alert.xml", Properties.Settings.Default.DataFolder + "/TransAlert.xml");
XmlSerializer serializer = new XmlSerializer(typeof(warnings));
fileStream = new FileStream(Properties.Settings.Default.DataFolder + "/TransAlert.xml", FileMode.Open);
result = (warnings)serializer.Deserialize(fileStream);
isFileProcessed = true;
}
catch
{
Thread.Sleep(100);
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
}
return new Ext.Net.MVC.PartialViewResult
{
RenderMode = RenderMode.AddTo,
ContainerId = containerId,
Model = result.warningList,
WrapByScriptTag = false
};
}
This solution worked for me but i think it will make my program slow. Is there a better way to do that?