C#/BinaryWriter: Weird Characters apprearing in Output Stream(C#/BinaryWriter:输出流中出现奇怪字符)
本文介绍了C#/BinaryWriter:输出流中出现奇怪字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难弄清楚是什么原因导致奇怪的字符出现在我的输出流中.完整代码@pastebinFiddler输出
注意到我的边界前面的"s
"、"X
"、"�
"吗?
s---------------634227387532666996
Content-Disposition: form-data; name='key'
c06f4d0cdf6f2cc652635a08be34973d
X---------------634227387532666996
Content-Disposition: form-data; name='type'
file
�---------------634227387532666996
Content-Disposition: form-data; name='image'; filename='application_osx_split.png'
Content-Type=image/png
�PNG
我的代码
var bound = "-------------" + DateTime.Now.Ticks.ToString();
var tmplField = "--" + bound + "
Content-Disposition: form-data; name='{0}'
{1}
";
var tmplFile = "--" + bound + "
Content-Disposition: form-data; name='{0}'; filename='{1}'
Content-Type={2}
";
....
using (var reqStream = req.GetRequestStream())
{
var reqWriter = new BinaryWriter(reqStream);
reqWriter.Write(string.Format(tmplField, "key", "c06f4d0cdf6f2cc652635a08be34973d"));
reqWriter.Write(string.Format(tmplField, "type", "file"));
reqWriter.Write(string.Format(tmplFile, "image", Path.GetFileName(filepath), "image/" + Path.GetExtension(filepath).Substring(1)));
reqWriter.Write(File.ReadAllBytes(filepath));
reqWriter.Write("
--" + bound + "--");
reqWriter.Flush();
}
更新
我注意到,如果我改为使用Stream&;二进制编写器的组合进行如下操作,我就可以避免这个问题。为什么会这样?
var reqWriter = new StreamWriter(reqStream);
reqWriter.Write(string.Format(tmplField, "key", "c06f4d0cdf6f2cc652635a08be34973d"));
reqWriter.Write(string.Format(tmplField, "type", "file"));
reqWriter.Write(string.Format(tmplFile, "image", Path.GetFileName(filepath), "image/" + Path.GetExtension(filepath).Substring(1)));
reqWriter.Flush();
var binWriter = new BinaryWriter(reqStream);
binWriter.Write(File.ReadAllBytes(filepath));
binWriter.Write("
--" + bound + "--");
binWriter.Flush();
推荐答案
BinaryWriter为字符串添加长度前缀。
改用StreamWriter。
这篇关于C#/BinaryWriter:输出流中出现奇怪字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:C#/BinaryWriter:输出流中出现奇怪字符


猜你喜欢
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01