我想创建一个小的 Windows 应用程序,它将在每个时间段自动转到我的站点,并检查它是否运行正常,如果发现它关闭、不工作或有错误“示例:404、网络错误、连接到数据库失败”,它会在我的屏幕上显示一条消息。
我如何知道使用任何 .NET 语言以编程方式存在错误?
最佳答案
使用 WebClient
可以很容易地做到这一点。它看起来像这样:
WebClient client = new WebClient();
try
{
string response =
client.DownloadString("http://www.example.com/tester.cgi");
// We at least got the file back from the server
// You could optionally look at the contents of the file
// for additional error indicators
if (response.Contains("ERROR: Something"))
{
// Handle
}
}
catch (WebException ex)
{
// We couldn't get the file.
// ... handle, depending on the ex
//
// For example, by looking at ex.Status:
switch (ex.Status)
{
case WebExceptionStatus.NameResolutionFailure:
// ...
break;
// ...
}
}
您可以将其连接到 Timer
的 Tick
事件或其他事件以定期进行检查。
关于c# - 我的网站是否已关闭、无法正常工作或出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/607846/