In C#, is there a way to add an XML node to a file on disk WITHOUT loading it first?

前端 未结 8 1991
后悔当初
后悔当初 2020-12-20 14:14

I have a very basic XML structure/file on disk which is something like:


    kdkdkdk         


        
8条回答
  •  没有蜡笔的小新
    2020-12-20 15:02

    Not with any XML API or tool.

    You could open the file as Text, find the Position of and start overwriting from there. And of course add the again.


    A quick and dirty approach, this is not very robust:

    • make sure you prep the initial file, there should be nothing (no whitespace) after the closing tag
    • make sure you use ASCII or UTF8 encoding

    ====

    string closeTag = "";
    int closeLength = Encoding.UTF8.GetBytes(closeTag).Length;
    
    var fs = System.IO.File.Open(filename, System.IO.FileMode.Open);
    fs.Position = fs.Length - closeLength;
    
    var writer = new StreamWriter(fs);  // after the Position is set
    
    writer.WriteLine(newTag);
    writer.Write(closeTag);  // NOT WriteLine !!
    
    writer.Close();
    fs.Close();
    

    And of course you know about using using() {} blocks.

提交回复
热议问题