3

我想将 a Stream(包含图像)的内容复制到 a StreamWriter(我正在编写 webrequest 的地方),到目前为止我无法做到这一点。

我试过imageStream.CopyTo(streamWriter);了,但没用,因为它只能将它复制到另一个 Stream 而不是 StreamWriter。

我希望有人能帮助我!

编辑:添加代码

request.BeginGetRequestStream((requestResult =>
{
    Stream stream = request.EndGetRequestStream(requestResult);
    using (StreamWriter streamWriter = new StreamWriter(stream))
    {
        streamWriter.WriteLine(boundary);
        streamWriter.WriteLine("Content-Disposition: form-data; name=\"json\"");
        streamWriter.WriteLine("Content-Type: text/plain; charset=utf-8");
        streamWriter.WriteLine("Content-Transfer-Encoding: 8bit");

        streamWriter.WriteLine(json);

        streamWriter.WriteLine(boundary);
        streamWriter.WriteLine("Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"");
        streamWriter.WriteLine("Content-Type: application/octet-stream");
        streamWriter.WriteLine("Content-Transfer-Encoding: binary");
        streamWriter.WriteLine("");

        streamWriter.Flush();

        image.CopyTo(streamWriter.BaseStream);
        // image.CopyTo(stream); // also not working

        streamWriter.WriteLine("");
        streamWriter.WriteLine(boundary);

        streamWriter.Close();
    }

    ExecuteRequest(this, request);

}), request);
4

1 回答 1

2

感谢@decyclone 我必须使用streamWriter.BaseStream并且重要的是在此之前使用 Stream.Flush() 否则它将以错误的顺序写入。

        request.BeginGetRequestStream((requestResult =>
        {
            using (StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(requestResult)))
            {
                streamWriter.WriteLine(boundary);
                streamWriter.WriteLine("Content-Disposition: form-data; name=\"json\"");
                streamWriter.WriteLine("Content-Type: text/plain; charset=utf-8");
                streamWriter.WriteLine("Content-Transfer-Encoding: 8bit");

                streamWriter.WriteLine(json);

                streamWriter.WriteLine(boundary);
                streamWriter.WriteLine("Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"");
                streamWriter.WriteLine("Content-Type: application/octet-stream");
                streamWriter.WriteLine("Content-Transfer-Encoding: binary");
                streamWriter.WriteLine("");

                streamWriter.Flush();

                streamWriter.CopyTo(stream.BaseStream);

                streamWriter.WriteLine("");
                streamWriter.WriteLine(boundary);

                streamWriter.Close();
            }

            ExecuteRequest(this, request);

        }), request);
于 2012-10-19T19:15:38.173 回答