6

我想在一个类中保留一个 XmlDocument 对象,并让方法对其进行更改并保存它。

using (FileStream fs = new FileStream(@"D:\Diary.xml", 
       FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fs);

    // ... make some changes here

    xmlDoc.Save(fs);
}

上面的代码在文件中创建了两个 xml 结构的副本。

4

4 回答 4

3

尝试

fs.SetLength(0);

保存通话之前

于 2010-02-25T11:22:05.243 回答
2

添加:

fs.Position = 0;

在保存调用之前。

于 2010-02-25T11:00:31.943 回答
0

傻瓜解决方案中的 fs.Position 不起作用似乎有点奇怪。

一个等价物是

fs.Seek(0, SeekOrigin.Begin);

或者

而不是使用相同的文件流:

            //OrigPath is the path you're using for the FileReader

            System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(OrigPath);
            xmlDoc.Save(writer);
            writer.Close();
于 2010-02-25T11:31:21.397 回答
0

或者,即使这样也可以工作......

        XmlDocument xmlDoc = new XmlDocument( );
        xmlDoc.Load( @"D:\Diary.xml" );

        //.... make some changes here
        XmlText node = xmlDoc.CreateTextNode( "test" );
        xmlDoc.DocumentElement.AppendChild( node );

        xmlDoc.Save( @"D:\Diary.xml" );
于 2010-02-25T11:36:21.590 回答