6

クラス内に 1 つの 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 構造の 2 つのコピーを作成します。

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 に答える