我正在重温我的一些旧代码,偶然发现了一种根据网址获取网站标题的方法。这并不是真正意义上的稳定方法,因为它经常无法产生结果,有时甚至会产生不正确的结果。此外,有时它无法显示标题中的某些字符,因为它们是另一种编码。
有没有人对这个旧版本有改进的建议?
public static string SuggestTitle(string url, int timeout)
{
WebResponse response = null;
string line = string.Empty;
try
{
WebRequest request = WebRequest.Create(url);
request.Timeout = timeout;
response = request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
StreamReader streamRead = new System.IO.StreamReader(streamReceive, encoding);
while(streamRead.EndOfStream != true)
{
line = streamRead.ReadLine();
if (line.Contains("<title>"))
{
line = line.Split(new char[] { '<', '>' })[2];
break;
}
}
}
catch (Exception) { }
finally
{
if (response != null)
{
response.Close();
}
}
return line;
}
最后一点 - 我希望代码也能运行得更快,因为它会阻塞直到页面被获取,所以如果我只能获取站点标题而不是整个页面,那就太好了。
最佳答案
获取内容的更简单方法:
WebClient x = new WebClient();
string source = x.DownloadString("http://www.singingeels.com/");
获取标题的更简单、更可靠的方法:
string title = Regex.Match(source, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>",
RegexOptions.IgnoreCase).Groups["Title"].Value;
关于c# - 如何从c#获取网站标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/329307/