.net - In C# how do I get the file position of each text row in an output file (as it is being written)? -


as write text lines temp file, i'd store file position of each line future random access.

this not work

 streamwriter outfile;   { ...           fpos[i++] = outfile.basestream.position;  } 

fpos values in above loop 0,0,0,...,1024,1024,...2028,2048 etc - i.e. physical positions.

the following work away buffering:

 { ...           outfile.flush();           fpos[i++] = outfile.basestream.position;  } 

is there better way (logical) file position go without giving buffering ?

if data small enough fit in memory, have streamwriter write memorystream. flush after each line, , memory stream's position before writing each line. , when you're done writing data memory stream, copy file.

if data larger fit in memory, use memorystream buffer, , flush memory stream disk file whenever fills up. take little bookkeeping, wouldn't terrible.

slightly more involved create own class derived bufferedstream counts bytes written it. open stream writer buffer size of 0, , have write buffered stream. query buffered stream number of bytes written. of course, stream write file stream. it'd like:

using (var fs = new filestream(...)) {     using (var buff = new custombufferedstream(fs))     {         using (var writer = new streamwriter(buff, encoding))         {             ... output here         }     } } 

you might not able have streamwriter buffer size of 0. if that's case, you'll have flush after every line, , might have override custom stream's flush method doesn't automatically flush disk file. don't recall if streamwriter.flush automatically calls basestream.flush.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -