0

I have a text stream data like :

<dimension>{{count}}</dimension>
<v>1</v>
<v>2</v>
<v>3</v>
....
<v>100000</v>

I use streamwriter to write data into a file (because I want to avoid OOM situation) and only after wrting all data then I colud know the dimension count.

So I'd like to replace {{count}} mark by the count after writing.

Steps logic like:

    var count = 0 ;
    using (var stream = File.Create(path))
    using (var writer = new StreamWriter(stream))
    using (var reader = GetReader())
    {
        while(reader.Read())
            count++;
            writer.Write(reader.GetValue());
        } 
        
        //Go to file top and edit/update/replace `{{count}}`
        stream.TopReplace("{{count}}",count);
    }

I've read :

so right now my way is read all data into memory then edit on it, but it loss streamwriter point...

Wei Lin
  • 3,591
  • 2
  • 20
  • 52
  • 1
    You could write a 33 character (`` + 10 digits (max length of an int value) + `` comes to 33 characters) line at the start of the file. Once you've finished writing everything, seek back to the beginning and write (not writeline) your `count`. This would leave whitespace after the closing tag, but it's XML so it shouldn't matter (unless someone is parsing it by hand and not ignoring whitespace). – ProgrammingLlama Mar 25 '21 at 10:27
  • 1
    Failing that, you'll have to read the file line-by-line and write a new file. – ProgrammingLlama Mar 25 '21 at 10:28
  • 2
    *"only after wrting all data then I colud know the dimension count"* - you may want to make your implementation mockable to be able to simulate writing in first pass, obtain missing values and then do a real writing with all values known. – Sinatr Mar 25 '21 at 10:30
  • thanks @Llama I'm trying it now – Wei Lin Mar 25 '21 at 11:15
  • @Sinatr yes, I want it. – Wei Lin Mar 25 '21 at 11:16

0 Answers0