john G john G - 1 year ago 113
ASP.NET (C#) Question

unable to write uni-code charecters inside a File, values are being trimmed

I am working on an mvc web application, and i wrote the following code to create some txt files , as follow:-

using (FileStream fs = File.Create(serverpath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".txt"))
var tt = Encoding.UTF8.GetBytes(resourceinfo.operation.Details.PASSWORD);
fs.Write(Encoding.UTF8.GetBytes(resourceinfo.operation.Details.PASSWORD), 0, mainresourceinfo.operation.Details.PASSWORD.Length);

now in my case if the
it will be saved inside the txt file as
so can anyone advice on this please ?

Answer Source

Make sure you write the complete byte array.

UTF8 is an encoding that encodes characters in 1, 2, 3 of 4 bytes. If you encode a string to a byte array you can't no longer use the original string length as an indicator for the number of bytes you have to write

 // get the bytes in some encoding
 var bytes = Encoding.UTF8.GetBytes(resourceinfo.operation.Details.PASSWORD);
 // write all the bytes, using the array length and not the string lenght
 fs.Write(bytes, 0, bytes.Length);

Do note that you could use a StreamWriter to wrap your filestream and have the StreamWriter handle the encoding for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download