2

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.

default
  • 11,485
  • 9
  • 66
  • 102
  • 1
    Does this method help: http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx ? – Vitalii Mar 25 '13 at 10:22
  • 1
    duplicate of http://stackoverflow.com/questions/8464261/filestream-and-streamwriter-how-to-truncate-the-remainder-of-the-file-after-wr ? – Lanorkin Mar 25 '13 at 10:23

2 Answers2

3

You'll have to use FileStream.SetLength like this:

stream.SetLength(stream.Position);

After you have finished writing.
Of course, assuming that the position is at the end of the written data.

Vercas
  • 8,931
  • 15
  • 66
  • 106
2

Why do you read the file into a filestream first?

You can do the following:

private static void Main(string[] args]
{
   string path = "MyFile.xml";
   XDocument doc = XDocument.Load(path);
   // Check if the root-Node is not null and other validation-stuff
   doc.Descendants("data").First().Value = "less data";
   doc.Save(path);
}

The problem with the stream is, that you can either read or write.

I've read, that with the .net-Framework 4.5 it's also possible to read and write on a stream, but haven't tried it yet.

Tomtom
  • 9,087
  • 7
  • 52
  • 95