无法在File中编写单代码字符,正在修剪值

时间:2016-08-03 16:01:49

标签: c# asp.net .net asp.net-mvc

我正在开发一个ASP.NET MVC Web应用程序,我编写了以下代码来创建一些txt文件,如下所示: -

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);
}

现在我的情况是,如果resourceinfo.operation.Details.PASSWORD == £¬£¬它将作为£¬保存在txt文件中,那么有人可以就此提出建议吗?

1 个答案:

答案 0 :(得分:1)

确保编写完整的字节数组。

UTF8是一种编码,用于编码4个字节中的1,2,3个字符。如果将字符串编码为字节数组,则不能再使用原始字符串长度作为必须写入的字节数的指示符

 // 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);

请注意,您可以使用StreamWriter打包文件流并让StreamWriter为您处理编码。