Read multipart/mixed in C# (.NET 4.0)

一笑奈何 提交于 2019-12-05 08:46:24

Use ReadAsMultipartAsync in the System.Net.Http.Formatting assembly, along the lines of

var content   = new StreamContent (stream) ;
var multipart = await content.ReadAsMultipartAsync () ;
foreach (var part in multipart)
{
    if (part.Headers.ContentType.MediaType == "application/json")
    {
        // deserialize via stream e.g. part.ReadAsStreamAsync () or via string
        // using part.ReadAsStringAsync () to avoid charset grief
    }
    else
    using (var file = File.Create (parser.Filename))
        await part.CopyToAsync (file) ;
}

This ought to get you started.

I managed to solve my problem (read the multipart that is), but had to move to .NET 4.5 , if anyone knows the changes in order to work in .NET 4.0 (by replacing "await" and "async" with something else I guess) I would love to know. So that's what I did.

  static void Main(string[] args)
  {

            //some code here...

            // POST the request
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Console.Write(httpResponse.GetResponseStream());
            readMultipart(httpResponse).Wait();
    }

    async static Task readMultipart(HttpWebResponse httpResponse)
    {
         var content = new StreamContent(httpResponse.GetResponseStream());
        content.Headers.Add("Content-Type", httpResponse.ContentType);
        var multipart = await content.ReadAsMultipartAsync();
        String filename = "";
        String json = await multipart.Contents[0].ReadAsStringAsync();
        JObject o = JObject.Parse(json);
        filename = o["fileName"].ToString();
        using (var file = File.Create("C:\\testWS\\" + filename))
            await multipart.Contents[1].CopyToAsync(file);
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!