如何在C#中将post字节数组或字符串作为文件

时间:2015-08-19 09:50:39

标签: c# post file-upload webclient

我需要将xml字符串作为文件发布。这是我的代码:

using (WebClient client = new WebClient())
{
    client.UploadData(@"http://example.com/upload.php",
                      Encoding.UTF8.GetBytes(SerializeToXml(entity)));
}

它成功发布数据,但服务器无法将数据识别为上传文件。

我需要它与此类似的工作

using (WebClient client = new WebClient())
{
    client.UploadFile(@"http://example.com/upload.php", @"C:\entity.xml");
}

如何在不将xml保存到文件系统的情况下实现此目的?

1 个答案:

答案 0 :(得分:0)

使用HttpClient

解决了问题
using (var client = new HttpClient())
{
    using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
    {
        using (var stream = GenerateStreamFromString(SerializeToXml(p)))
        {
            StreamContent streamContent = new StreamContent(stream);
            streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            content.Add(streamContent, "file", "post.xml");

            using (var message = client.PostAsync("http://example.com/upload.php", content).Result)
            {
                string response = message.Content.ReadAsStringAsync().Result;
            }
        }
    }
}

public static Stream GenerateStreamFromString(string str)
{
    byte[] byteArray = Encoding.UTF8.GetBytes(str);
    return new MemoryStream(byteArray);
}