content.Add
的以下行是否会使对象无法正确处理?如果是这样,处理这个问题的正确方法是什么。
public string UploadGameToWebsite(string filename, string url, string method = null)
{
var client = new HttpClient();
var content = new MultipartFormDataContent();
content.Add(new StreamContent(File.Open(filename, FileMode.Open, FileAccess.Read)), "Game", "Game.txt");
var task = client.PutAsync(url, content);
var result = task.Result.ToString();
return result;
}
答案 0 :(得分:6)
StreamContent
,它还会处理基础FileStream
。using
语句。ToString
上的HttpResponseMessage
,也许状态代码会更有用,或者看看StatusCode = 200并返回布尔值(true / false)?代码:
public async Task<string> UploadGameToWebsiteAsync(string filename, string url, string method = null)
{
HttpClient client = null;
StreamContent fileStream = null;
try
{
client = new HttpClient();
fileStream = new StreamContent(System.IO.File.Open(filename, FileMode.Open, FileAccess.Read))
var content = new MultipartFormDataContent();
content.Add(fileStream, "Game", "Game.txt");
HttpResponseMessage result = await client.PutAsync(url, content);
return result.ToString();
}
finally
{
// c# 6 syntax
client?.Dispose();
fileStream?.Dispose(); // StreamContent also disposes the underlying file stream
}
}
使用using
块的代码版本#2。
public async Task<string> UploadGameToWebsiteAsync(string filename, string url, string method = null)
{
using (var client = new HttpClient())
{
using (var fileStream = new StreamContent(System.IO.File.Open(filename, FileMode.Open, FileAccess.Read)))
{
var content = new MultipartFormDataContent();
content.Add(fileStream, "Game", "Game.txt");
HttpResponseMessage result = await client.PutAsync(url, content);
return result.ToString();
}
}
}
答案 1 :(得分:0)
是的,它会。 File.Open返回应该处理的流。最简单的方法是使用&#34;使用&#34;块,像这样:
public string UploadGameToWebsite(string filename, string url, string method = null)
{
var client = new HttpClient();
var content = new MultipartFormDataContent();
using (var fileStream = File.Open(filename, FileMode.Open, FileAccess.Read))
{
content.Add(new StreamContent(fileStream), "Game", "Game.txt");
var task = client.PutAsync(url, content);
var result = task.Result.ToString();
return result;
}
}