I have sample.text file ( UTF8 encoded format) having maximum size of 200 character. I have 2 line of data(word count=38 and total byte count=40) present in sample.text file as given below:
---------------------------------------------
019aIŞLET NO : 044
019aIŞLET NO :
045
---------------------------------------------
Here i need to write new data (assume new data is string newData="Hello C#.NET" at the end of file. here is snippet code for that:
------------------------------------------------
var file = new FileInfo(sample.text);
var contentUTF8 = File.ReadAllText(file.FullName, Encoding.UTF8);
FileStream fileStream = new FileStream(sample.text, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, 8192, FileOptions.WriteThrough);
fileStream.SetLength(200);
fileStream.Position = Encoding.UTF8.GetByteCount(contentUTF8);
StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
streamWriter.Write(newData);
streamWriter.Flush();
------------------------------------------------
Since total byte length present sample.text is 40, above sample code should write newData from 41st position BUT while writing newData to sample.text file it overrides last 3 character of second line of sample.text file.
New sample.text file becomes as given below:
-------------------------------------
019aIŞLET NO : 044
019aIŞLET NO :
Hello C#.NET
-------------------------------------
But sample.text should looks(in expected case) like:
-------------------------------------
019aIŞLET NO : 044
019aIŞLET NO :
045Hello C#.NET
-------------------------------------
Conclusion of issue is this irrespective of input file length when i am writing newData to my file it always overrides last 3 characters. This is happening only in case of UTF8 encoding.
In case of ANSI encoded file it works fine without any issue.
Can anybody tell me why my sample code(streamWriter.Write(newData)) is overriding last 3 characters of my existing UTF8 encoded file?
I hope i have tried to explain problem properly, please let me know in case more information is required.