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

本文关键字:数组 字符串 文件 字节数 字节 post http | 更新日期: 2023-09-27 18:08:45

我需要发布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保存到文件系统,我怎么能做到这一点?

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

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