I'm trying to find the most reasonable way to open a file, modify its content and then write it back to file.
If I have the following "MyFile.xml"
<?xml version="1.0" encoding="utf-8"?>
<node>
<data>this is my data which is long</data>
</node>
And then want to modify it according to this:
private static void Main(string[] args)
{
using (FileStream stream = new FileStream("Myfile.xml", FileMode.Open))
{
XDocument doc = XDocument.Load(stream);
doc.Descendants("data").First().Value = "less data";
stream.Position = 0;
doc.Save(stream);
}
}
I get the following result. Note that, since the total file length is less than before I get incorrect data at the ending.
<?xml version="1.0" encoding="utf-8"?>
<node>
<data>less data</data>
</node>/node>
I guess I could use File.ReadAll*
and File.WriteAll*
but that would mean two File openings. Isn't there some way to say "I want to open this file, read its data and when I save delete the old content" without closing and reopening the file? Other solutions that I have found include FileMode.Truncate
, but that would imply that I cannot read the content.