gpt4 book ai didi

c# - 如何以 UTF-8 格式制作 Stream.Write() 输出

转载 作者:太空狗 更新时间:2023-10-29 18:23:13 25 4
gpt4 key购买 nike

我的问题是:

我正在使用 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,但它不起作用。

最佳答案

请记住,对于流,您几乎总是可以根据需要包装流。如果您想编写 UTF-8 编码的内容,请使用正确的编码将请求流包装在 StreamWriter 中:

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

既然你说你要上传到网络服务,一定要设置你的内容编码。由于您没有发布 request 对象的来源,我假设它是一个正常的 HttpWebRequest .

对于 HttpWebRequest,您可以使用 ContentType 属性告诉服务器内容编码是什么。

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

不过,正如其他人所提到的,FTP 传输本身也可能会破坏它。如果可以,请确保它以二进制模式传输,而不是 ASCII 模式。

关于c# - 如何以 UTF-8 格式制作 Stream.Write() 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7722642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com