下面的行是否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;
}
Run Code Online (Sandbox Code Playgroud)
StreamContent它也处理底层FileStream.using语句.ToString的HttpResponseMessage,也许状态代码会更加有用或看的StatusCode = 200,并返回布尔(真/假)?码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
代码版本#2使用using块.
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)