本文介绍了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:输出流中出现奇怪字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!