C# POST Form

public string HttpPostForm(string url,Dictionary<string,string> _form,string _filepath="")
{
	try
	{
		var formData = new MultipartFormDataContent();
		_form.Cast<KeyValuePair<string, string>>().ToList().ForEach(a =>
		{
			formData.Add(new StringContent(a.Key), a.Value);
		});
		if(_filepath.IsNotEmpty())
		{
			byte[] data = System.IO.File.ReadAllBytes(_filepath);
			formData.Add(new ByteArrayContent(data), "file", new FileInfo(_filepath).Name);
		}
		var result = new HttpClient().PostAsync(url, formData).Result.Content.ReadAsStringAsync().Result;
		Fmath.RunLog($"HttpPostForm:{url}\r\n{_form.ToJson()}\r\n{result}");
		return result;
	}
	catch (Exception Err)
	{
		Fmath.RunLog($"HttpPostForm:{url}\r\n{_form.ToJson()}\r\n{Err.Message}");
		return "";
	}
}
posted @ 2025-11-05 23:39  随风3971  阅读(7)  评论(0)    收藏  举报