如何返回 Stream 变量,使其不为空
本文关键字:变量 Stream 何返回 返回 | 更新日期: 2023-09-27 18:34:11
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 为空。所以它会抛出异常。而且我无法为流创建实例。那么我还能为 Stream s 分配什么,以防它返回而不输入?
您可以返回 Stream.Null,但您应该立即处理错误。
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);
}
}