XmlDocument Save keeps file open

2019-06-15 16:12发布

I have a simple c# function that creates a basic XML file and saves:

private void CreateXMlFile(string Filename, string Name, string Company)
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            XmlNode licenseNode = doc.CreateElement("license");
            doc.AppendChild(licenseNode);

            XmlNode node = doc.CreateElement("Name");
            node.AppendChild(doc.CreateTextNode(Name));
            licenseNode.AppendChild(node);

            node = doc.CreateElement("Company");
            node.AppendChild(doc.CreateTextNode(Company));
            licenseNode.AppendChild(node);


            doc.Save(Filename);
        }

When I try to edit or delete the file I always get following error:

The process cannot access the file because it is being used by another process.

XmlDocument doesnt have any inbuilt dispose or close routines and wondered how I can force the file to close before later editing or deleting it.

I have tried to save the file using StreamWriter:

StreamWriter outStream = System.IO.File.CreateText(outfile);
            outStream.Write(data);
            outStream.Close();

But this didnt make a difference with the same error.

Your advice is greatly accepted.

Thank you

2条回答
时光不老,我们不散
2楼-- · 2019-06-15 16:47

Your code is fine. I tested it on my machine and there is no lock left after Save().

Try to use Unlocker (http://www.softpedia.com/get/System/System-Miscellaneous/Unlocker.shtml) to check whether you are really the one who holds the lock.

Which .NET framework do you use? Theres also a report (http://bytes.com/topic/net/answers/467028-xmldocument-save-does-not-close-file-properly) which was not reproducable too.

查看更多
戒情不戒烟
3楼-- · 2019-06-15 17:11

Send Stream to XmlDocument's Save method instead of file name.

    private static void Main(string[] args)
    {
        CreateXMlFile("c:\\test.xml", "testName", "testCompany");
    }

    private static void CreateXMlFile(string Filename, string Name, string Company)
    {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);

        XmlNode licenseNode = doc.CreateElement("license");
        doc.AppendChild(licenseNode);

        XmlNode node = doc.CreateElement("Name");
        node.AppendChild(doc.CreateTextNode(Name));
        licenseNode.AppendChild(node);

        node = doc.CreateElement("Company");
        node.AppendChild(doc.CreateTextNode(Company));
        licenseNode.AppendChild(node);
        StreamWriter outStream = System.IO.File.CreateText(Filename);

        doc.Save(outStream);
        outStream.Close();
    }

I tried executing above code and it is working fine at my end.

查看更多
登录 后发表回答