处理File.Open或StreamContent

时间:2016-03-02 16:37:55

标签: c# .net dispose

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;
        }

2 个答案:

答案 0 :(得分:6)

  1. 如果您要在方法中调用异步操作,请使您的方法异步。
  2. 处置您的文件流以及客户端。在下面的示例中,通过部署StreamContent,它还会处理基础FileStream
  3. 我更喜欢使用finally块来处理多个一次性对象,它也非常适合嵌套using语句。
  4. 不确定为什么要返回ToString上的HttpResponseMessage,也许状态代码会更有用,或者看看StatusCode = 200并返回布尔值(true / false)?
  5. 代码:

    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;
        }
    }