C#/BinaryWriter:输出流中出现奇怪字符

C#/BinaryWriter: Weird Characters apprearing in Output Stream(C#/BinaryWriter:输出流中出现奇怪字符)
本文介绍了C#/BinaryWriter:输出流中出现奇怪字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚是什么原因导致奇怪的字符出现在我的输出流中.完整代码@pastebin

Fiddler输出

注意到我的边界前面的"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:输出流中出现奇怪字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)