简体   繁体   中英

C#/BinaryWriter: Weird Characters apprearing in Output Stream

I am having difficulties figuring out what is causing wierd characters to appear in my output stream ... full code @pastebin

Fiddler output

notice the " s ", " X ", " " before my boundary?

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

my code

var bound = "-------------" + DateTime.Now.Ticks.ToString();
var tmplField = "--" + bound + "\r\nContent-Disposition: form-data; name='{0}'\r\n\r\n{1}\r\n";
var tmplFile = "--" + bound + "\r\nContent-Disposition: form-data; name='{0}'; filename='{1}'\r\nContent-Type={2}\r\n\r\n";

....

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("\r\n--" + bound + "--");
    reqWriter.Flush();
}

UPDATE

I noticed that if i did something like below instead, using a combination of Stream & Binary Writers, I can avoid the problem. Why is this so?

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("\r\n--" + bound + "--");
binWriter.Flush();

BinaryWriter prefixes strings with their length.

Use a StreamWriter instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM