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

How to http post byte array or string as file in C#

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

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

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

我需要它像这样工作

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

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

使用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);
}