c# - Understanding Stream.Write Method to overwrite existing text -
i used streamwriter write records file. want overwrite specific record.
string file="c:\\......"; streamwriter sw = new streamwriter(new filestream(file, filemode.open, fileaccess.write)); sw.write(...); sw.close();
i read somewhere here can use stream.write method that, have no previous experience or knowledge of how deal bytes.
public override void write( byte[] array, int offset, int count )
what have string how use method. need explain byte[] array , int count are, , simple sample code shows how use method overwrite existing record in file.
ex. have record mark1287,11100,25| change bill9654,22100,30| .
if want override particular record, must use filestream.seek
-method set put stream in position.
example seek
using system; using system.io; class fstream { static void main() { const string filename = "test#@@#.dat"; // create random data write file. byte[] dataarray = new byte[100000]; new random().nextbytes(dataarray); using(filestream filestream = new filestream(filename, filemode.create)) { // write data file, byte byte. for(int = 0; < dataarray.length; i++) { filestream.writebyte(dataarray[i]); } // set stream position beginning of file. filestream.seek(0, seekorigin.begin); // read , verify data. for(int = 0; < filestream.length; i++) { if(dataarray[i] != filestream.readbyte()) { console.writeline("error writing data."); return; } } console.writeline("the data written {0} " + "and verified.", filestream.name); } } }
after having sought position, use write
, whereas
public override void write( byte[] array, int offset, int count ) parameters array type: system.byte[] buffer containing data write stream. offset type: system.int32 zero-based byte offset in array begin copying bytes stream. count type: system.int32 maximum number of bytes write.
and important: consider documentation when unsure!