c# - 好的示例.Net Windows服务可报告错误

标签 c# windows-services error-handling monitoring notifications

我正在编写Windows服务,它将进行大量的网络通信(复制共享文件夹中的许多文件并修改数据库)。

我需要一种方法来通知用户(如果已登录)任何异常/错误。我的问题是将错误分组(通过电子邮件将其发送到管理员地址)。

我知道事件日志记录既没有系统托盘中的通知气泡,但管理员没有查看该日志,他更喜欢电子邮件。

理想的组件是ASP.NET运行状况监视,但仅适用于IIS,并且它是Windows服务所需的类似组件。

关于此问题的任何示例应用程序Windows Service(使用C#或.net语言)(带有源代码)?

最佳答案

如果您只需要一种发送电子邮件通知的方法,.Net可以使用SMTP和邮件类型来解决此问题。电子邮件通知在软件中不再常见,这就是为什么常用功能已合并到基类库中的原因。

您可以使用SmtpClient,MailAddress和MailMessage对象来完成仅发送电子邮件通知所需的操作。当然,您需要有权访问SMTP服务器以传输邮件,因此请找出其主机地址是什么,以正确配置您的应用程序。这里有一些例子:

SmtpClient  mailClient = new SmtpClient("smtp.fu.bar");
MailAddress senderAddr = new MailAddress("you@fu.bar");
MailAddress  recipAddr = new MailAddress("admin@fu.bar");
MailMessage   emailMsg = new MailMessage( senderAddr, recipAddr );

emailMsg.Subject = "Test email.";
emailMsg.Body = "Here is my email string which serves as the body.\n\nSincerely,\nMe";
mailClient.Send( emailMsg );

该示例只是简单的代码,但最好将其放入这样的可重用方法中:
public void SendNotification( string smtpHost, string recipientAddress, string senderAddress, string message, string subject )
{
    SmtpClient  mailClient = new SmtpClient(smtpHost);
    MailMessage   emailMsg = new MailMessage( new MailAddress(senderAddress), new MailAddress(recipientAddress) );

    emailMsg.Subject = subject;
    emailMsg.Body = message;

    mailClient.Send( emailMsg );
}

关于c# - 好的示例.Net Windows服务可报告错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3257587/

相关文章:

c# - 有没有办法等待多个信号量

c# - Web Api 2 不反序列化 JSON

c# - 来自 C# Windows 服务的 Facebook 状态更新

c# - 为什么内部异常到达 ThreadException 处理程序而不是实际抛出的异常?

c# - 获取共享计算机上的目录列表 .NET

windows - VB.NET 定时器问题

batch-file - 通过bat解决 “The specified service has been marked for deletion”错误

java - 为什么Eclipse无法连接到VM? ( socket 关闭)

excel - 如何处理: Run-time error '53' File not found错误

error-handling - FileSystemWatcher和BackgroundWorker的全局错误处理程序