John John
John John

Reputation: 1

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

I am working on an ASP.NET 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 resourceinfo.operation.Details.PASSWORD == £¬£¬ it will be saved inside the txt file as £¬ so can anyone advice on this please?

Upvotes: 0

Views: 35

Answers (1)

rene
rene

Reputation: 42453

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.

Upvotes: 1

Related Questions