如何使 Stream.Write() 以 UTF-8 格式输出
我的问题是这样的:
我正在使用 ASP.NET 生成并上传 SQL 文件,但是将文件保存到 FTP 服务器后,ü 等字符更改为 &uul;、ø 更改为 ø 等等...如何解决我可以阻止这种情况发生吗?我不希望文件采用 ASCII 代码格式,而是采用 UTF-8 格式。
生成和上传文件的代码如下所示:
//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
,但它不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请记住,对于流,您几乎总是可以根据需要包装流。如果您想编写 UTF-8 编码内容,请使用正确的编码将请求流包装在
StreamWriter
中:既然您说您要上传到 Web 服务,请务必设置您的内容编码。由于您尚未发布
request
对象的来源,因此我假设它是一个正常的 HttpWebRequest。对于 HttpWebRequest,您可以使用
ContentType
属性告诉服务器内容编码是什么。不过,正如其他人提到的,FTP 传输本身也可能会破坏它。如果可以的话,请确保它以二进制模式而不是 ASCII 模式传输。
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: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.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.
将其放入调试中,并查看调用 encoding.GetBytes() 后在“缓冲区”中放入的内容。这将验证是否是接收端造成的。
Put it in debug and look at what gets put in 'buffer' after encoding.GetBytes() is called. This will verify if it's the rx side causing it.