苏飞论坛

标题: 我想做一个服务 监控文件夹 自动发送邮件 最好是多线程的 我自己做了一个出错 [打印本页]

作者: 寻找北极星    时间: 2013-11-1 21:29
标题: 我想做一个服务 监控文件夹 自动发送邮件 最好是多线程的 我自己做了一个出错
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;
namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
       string WatcherDirectory = "d:\\文件";
        protected override void OnStart(string[] args)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\文件\\log.txt", true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
            }
        }
        protected override void OnStop()
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\文件\\log.txt", true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
            }
        }
        private void StartThread(object arg)
        {
            FileSystemEventArgs e = (FileSystemEventArgs)arg;
            Sends(e);
        }
        private bool RegexMailValid(string str)
        {
            string match = @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$";
            if (Regex.IsMatch(str, match))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void Sends(FileSystemEventArgs e)
        {
            try
            {
            string createdFileName = e.Name;
            MailAddress from = new MailAddress("5105155@qq.com");
            string toFileName = createdFileName.Substring(0,createdFileName.Length - 4);
            if (RegexMailValid(toFileName) == false) {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\文件\\log.txt", true))
                {
                    sw.WriteLine(e.Name + " 发送失败  名字错误");
                }
                return;
            }
            MailAddress to = new MailAddress(toFileName);
            
                //log created file name and send mail.
               
                //邮件主题、内容
                MailMessage message = new MailMessage(from, to);
                message.Subject = "流向";
                message.SubjectEncoding = System.Text.Encoding.UTF8;//5-1-a-s-p-x
                message.Body = "欢迎您";
                message.BodyEncoding = System.Text.Encoding.UTF8;
                //添加附件
                Attachment attachFile = new Attachment(e.FullPath);
                message.Attachments.Add(attachFile);
                //大部分邮件服务器均加smtp.前缀
                SmtpClient client = new SmtpClient("smtp." + from.Host);
                SendMail(client, from, "aaaaaa", to, message);
            }
            catch(Exception ex)
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\文件\\log.txt", true))
                {
                    sw.WriteLine(e.Name +" 发送失败");
                }
                throw;
            }
        }
          void PDFFileWatcher_Created(object sender, FileSystemEventArgs e)
        {
            try
            {
                Thread th = new Thread(new ParameterizedThreadStart(StartThread));  
                th.IsBackground = true;
                th.Start(e);
            }
            catch (Exception ex) { }         
        }
          //根据指定的参数发送邮件
          private void SendMail(SmtpClient client, MailAddress from, string password, MailAddress to, MailMessage message)
          {
              //不使用默认凭证,注意此句必须放在client.Credentials的上面
              client.UseDefaultCredentials = false;
              //指定用户名、密码
              client.Credentials = new NetworkCredential(from.Address, password);
              //邮件通过网络发送到服务器
              client.DeliveryMethod = SmtpDeliveryMethod.Network;
              try
              {
                  client.Send(message);
                  using (System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\文件\\log.txt", true))
                  {
                      sw.WriteLine( to+"  发送成功");
                  }
              }
              catch
              {
                  using (System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\文件\\log.txt", true))
                  {
                      sw.WriteLine(to+" 发送失败");
                  }
                  throw;
              }
              finally
              {
                  //及时释放占用的资源
                  message.Dispose();
              }
          }

    }
}






欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4