问题描述
我的问题是这样的:
我生成并上传使用ASP .NET中的sql文件,但该文件保存到FTP服务器后,像ü字符更改为&多山,O&来oslash;等等...我怎么能prevent这种情况发生?我不希望文件与ASCII code被格式化,而是用UTF-8。
my issue is this:I am generating and uploading an 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.
在code产生和上传文件看起来像这样:
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();
正如你可以看到我已经尝试使用 System.Text.UTF8Encoding
,但它不工作。
谢谢!
推荐答案
记住,用流可以在必要时几乎总是换流。如果你想编写UTF-8 EN codeD的内容你包在请求流的StreamWriter
通过正确的编码:
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);
}
既然你说你要上传到Web服务一定要设置您的内容编码为好。既然你没有张贴在该要求
对象来自,我会认为这是一个正常的HttpWebRequest.
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.
通过一个HttpWebRequest的,你会告诉服务器的内容编码是通过使用的ContentType
属性的东西。
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";
正如其他人所说,虽然,FTP传输本身可能破坏它。如果可以,确保它的二进制模式转移,而不是ASCII模式。
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.
这篇关于如何使Stream.Write()以UTF-8格式输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!