0

I am importing information from XML files into a SQL Database. The import is working fine but some of the XML files have errors in them so therefore the code fails. I catch the exception and try to move the file to an error folder but as I was previously reading from the file I get an error saying the file is in use by another process. I have searched but havent came across any way of curing this yet. I have tried saving the document but still is in use when I try to move, Below is a sample of the code where I try to move the file for reference. Any suggestions on how to cure this would be great and thanks in advance for the information.

XmlDocument doc = new XmlDocument();
try
{
    doc.Load(st);
}
catch(Exception ex)
{
    doc.Save(st);
    if (File.Exists(st))
        File.Move(st, st + "\\Error");
}
Daniel
  • 9,491
  • 12
  • 50
  • 66
Ryan McKinney
  • 183
  • 1
  • 2
  • 16
  • can you specify your folder structure. Where your XML file currently exists and where you are trying to move it ? – Afnan Ahmad Jan 09 '17 at 08:38
  • Are you sure it's XMLDocument holding it open? It should never do that since it just loads it in and that's that. – Sami Kuhmonen Jan 09 '17 at 08:42
  • `XmlDocument` is unable to load file content, but the file is still in use. Don't try to move the file, just copy it, and perform a cleanup later. – Diligent Key Presser Jan 09 '17 at 08:48
  • The folder structure is as follows, main/in is the import folder then once an error occurs I am trying to move it to main/error. The move works fine when the file imports correctly as I move it to a complete folder. – Ryan McKinney Jan 09 '17 at 09:16
  • See this topic: http://stackoverflow.com/questions/11015965/c-sharp-the-close-method-of-xml-loadfile I think doc = null and GC.Collect will help you. – rud0x1 Jan 09 '17 at 11:40

1 Answers1

0

Try

XmlDocument doc = new XmlDocument();
try
{
    doc.Load(st);
}
catch(Exception ex)
{
    //doc.Save(st);                      -- why do you need to save a file that exists?
    //if (File.Exists(st))               -- it returns always true
    //    File.Move(st, st + "\\Error"); -- wrong path

    File.Move(st, Path.Combine("C:\\Error", Path.GetFileName(st)));
}
user2316116
  • 6,726
  • 1
  • 21
  • 35
  • This worked thanks, the save, check if exists etc were jsut testing different things to see if it freed up the file. Thanks – Ryan McKinney Jan 11 '17 at 09:11