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

C# 如何在C中http将字节数组或字符串作为文件发布#,c#,post,file-upload,webclient,C#,Post,File Upload,Webclient,我需要将xml字符串作为文件发布。这是我的密码: using (WebClient client = new WebClient()) { client.UploadData(@"http://example.com/upload.php", Encoding.UTF8.GetBytes(SerializeToXml(entity))); } 它已成功发布数据,但服务器无法将数据识别为上载的文件 我需要它能像这样工作 using (WebCl

我需要将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保存到文件系统的情况下实现这一点?

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

你为什么反对使用文件系统?创建临时文件,上载,然后删除该文件。如果上传文件没有重载,这需要一个流,那么你只能创建临时文件。我相信上传数据可能会在标题和post数据中遗漏一些信息。它将字节作为普通字节上传。您可能需要为mime等设置一些标题——不过我可能错了。