我如何返回Stream变量,因此它不会为null?

时间:2016-02-11 19:13:16

标签: c# .net winforms

public static Image favicon(String u, string file)
{
    Stream s = 
    if (!u.Contains("blank") && u != "")
    {
        Uri url = new Uri(u);
        String iconurl = "http://" + url.Host + "/favicon.ico";

        WebRequest request = WebRequest.Create(iconurl);
        try
        {
            WebResponse response = request.GetResponse();

            s = response.GetResponseStream();
            return Image.FromStream(s);
        }
        catch (Exception ex)
        {
            return Image.FromFile(file);
        }
    }

    return Image.FromStream(s);
}

问题是最终s为null。所以它抛出异常。我不能为Stream做实例。那么我还可以为Stream分配什么,以防它返回时不进入?

2 个答案:

答案 0 :(得分:1)

您可以返回Stream.Null,但您应该立即处理错误。

答案 1 :(得分:0)

public static Image favicon(string u, string file)
{
    if (!String.IsNullOrEmpty(u) && !u.Contains("blank"))
    {
        // Check if this is a valid URL
        if (Uri.IsWellFormedUriString(u, UriKind.Absolute))
        {
            // Create the favicon.ico URL
            var url = new Uri(u);
            var iconUrl = $"http://{url.Host}/favicon.ico";

            // Try and download the icon
            var client = new WebClient();
            try
            {
                return Image.FromStream(client.OpenRead(iconUrl));
            }
            catch (WebException)
            {
                // If there was an error download the favicon, just return the file
                return Image.FromFile(file);
            }
        }
        else
        {
            throw new ArgumentException("Parameter 'u' is not a valid URL");
        }
    }
    else
    {
        return Image.FromFile(file);
    }
}