Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Stream.Write() output in UTF-8 format

My issue is this:

I am generating and uploading a SQL file using ASP.NET, but after the file is saved to the FTP server, characters like ü are changed to &uul;, ø to ø and so on... How can I prevent this from happening? I don't want the file to be formatted with ASCII code, but with UTF-8.

The code that generates and uploads the file looks like this:

//request = the object to be made an request out of.
Stream requestStream = request.GetReguestStream();
var encoding = new UTF8Encoding();
//fileContent is the string to be saved in the file
byte[] buffer = encoding.GetBytes(fileContent); 
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();

As you can see I've tried to use the System.Text.UTF8Encoding, but it doesn't work.

like image 672
linnkb Avatar asked Oct 11 '11 07:10

linnkb


1 Answers

Remember, with streams you can almost always wrap the streams as necessary. If you want to write UTF-8 encoded content you wrap the request stream in a StreamWriter with the correct encoding:

using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8)) {
  writer.Write(fileContent);
}

Since you say you're uploading to a web service be sure to set your content encoding as well. Since you haven't posted where the request object comes from, I'll assume it's a normal HttpWebRequest.

With a HttpWebRequest you would tell the server what the content encoding is by using the ContentType property.

request.ContentType = "text/plain;charset=utf-8";

As others have mentioned, though, the FTP transfer itself may be breaking it too. If you can, make sure it's transferred in binary mode, not ASCII mode.

like image 91
Joshua Avatar answered Sep 28 '22 15:09

Joshua