windows域账户模拟

using System.Security.Principal;
using System.Reflection.Emit;
using System.Diagnostics;

namespace TopsAdmin_Batch
{
    internal static class WinLogonHelper
    {
        /// <summary>
        /// 模拟windows登录域
        /// </summary>
        [DllImport("advapi32.DLL", SetLastError = true)]
        public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
    }

    class Program
    {
        static void Main(string[] args)
        {
            const int Time_17H = 61200000;
            const int Time_30M = 1800000;
            const int Time_10M = 600000;
            string userName = SCC.AppSettings["userName"].Trim();
            string domain = SCC.AppSettings["domain"].Trim();
            string pwd = SCC.AppSettings["pwd"].Trim();
            IntPtr admin_token = default(IntPtr);
            WindowsIdentity wid_admin = null;
            WindowsImpersonationContext wic = null;
            string catchEamilTo = System.Configuration.ConfigurationManager.AppSettings.Get("CatchMailTo");
            //在程序中模拟域帐户登录
            if (WinLogonHelper.LogonUser(userName, domain, pwd, 9, 0, ref admin_token) != 0)
            {
                using (wid_admin = new WindowsIdentity(admin_token))
                {
                    using (wic = wid_admin.Impersonate())
                    {
                        try
                        {
                            while (true)
                            {
                                DataTable dt = new DB().getDataTable("select * from MoveFile");//程序永远不退出,将dt定义在While里面,以适应数据库可能的变动
                                testMoveFile.fileDt = dt;
                                testMoveFile tmf = new testMoveFile();
                                tmf.deleteLog();
                                List<DataRow> EinLstList = new List<DataRow>();
                                int count = 0;//记录EIN LST 的总量// + HTML add by Ning

                                foreach (DataRow mydr in dt.Rows) //全盘文件处理,此时文件监视已取消
                                {
                                    tmf.init(mydr["FileType"].ToString());
                                    if ("EIN,LST,HTML".IndexOf(mydr["t"].ToString().Trim()) != -1) //modify by Ning
                                    {
                                        count++;
                                        EinLstList.Add(mydr);
                                    }
                                    //tmf.movefile(mydr["s"].ToString(), mydr["d"].ToString(), mydr["t"].ToString().ToUpper(), mydr["partten"].ToString(), mydr["FileType"].ToString().ToUpper());// test
                                    tmf.movefile(@"C:UsershmswhluDesktopasd89TC3000 HTML 0".ToString(), @"C:UsershmswhluDesktopasd89TC3000 HTML".ToString(), "LST".ToString().ToUpper(), @"".ToString(), "TC".ToString().ToUpper());
                                    //(?<first>^[A-Za-z0-9]+[-]{1}[a-z|A-Z]{0,1})(?<other>([d]{5})([a-z|A-Z])([^.]*))$
                                }

                                FileSystemWatcher[] th = new FileSystemWatcher[count];//监视EIN LST 文件的创建事件
                                DataRow dr;
                                for (int j = 0; j < EinLstList.Count; j++)
                                {
                                    dr = EinLstList[j];
                                    task mytask = new task(dr["d"].ToString(), dr["t"].ToString(), dr["FileType"].ToString(), dr["partten"].ToString(), tmf);
                                    th[j] = new FileSystemWatcher(dr["s"].ToString());
                                    th[j].IncludeSubdirectories = false;
                                    th[j].NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                                    th[j].Filter = "*." + dr["t"].ToString();
                                    th[j].Created += new FileSystemEventHandler(mytask.startWork);//有文件被创建,进行处理
                                    th[j].EnableRaisingEvents = true;
                                }
                                while (DateTime.Now.Hour < 23)//今天结束之前,不让程序住下执行(用户要求每天运行一次)
                                {
                                    Thread.Sleep(Time_30M);
                                }
                                //进入第二天
                                Thread.Sleep(Time_17H);//程序等待到接近19:00

                                while (DateTime.Now.Hour < 19 || DateTime.Now.Minute < 30)//下午七点半附近触发
                                {
                                    Thread.Sleep(Time_10M);//十分钟
                                }

                                for (int j = 0; j < EinLstList.Count; j++)//取消对EIN LST文件的监视,等待进入全文件夹扫描
                                {
                                    th[j].EnableRaisingEvents = false;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            new Email().SendMail("TopsAdmin_batch 异常", "HWSSHT@ASMPT.com", catchEamilTo, "", "", null, ex.Message, System.Net.Mail.MailPriority.Normal);
                        }
                    }
                }
            }

        }

        protected class task
        {
            private testMoveFile tmf=new testMoveFile();
            private string dDrie;
            private string type;
            private string filetype;
            private string partten;
            public task(string d, string t, string f, string p, testMoveFile tm)
            {
                dDrie = d;
                type = t;
                filetype = f;
                partten = p;
                tmf = tm;
            }
            public void startWork(object sender, FileSystemEventArgs e)
            {
                string catchEamilTo = System.Configuration.ConfigurationManager.AppSettings.Get("CatchMailTo");
                try
                {
                    tmf.init(filetype);
                   tmf.moveOneFile(e.FullPath, dDrie, type.ToUpper(), filetype.ToUpper(), partten);
                }
                catch (Exception ex)
                {
                    new Email().SendMail("TopsAdmin_batch 异常", "HWSSHT@ASMPT.com", catchEamilTo, "", "", null, ex.Message, System.Net.Mail.MailPriority.Normal);
                }
            }

        }
    }
}

发送邮件:

public void SendMail(string strSubject, string strFrom, string strTo, string strCc, string strBcc,string[] attFile, string strBody, System.Net.Mail.MailPriority MailPriority)
    {
        System.Net.Mail.MailMessage clsMailSvc;
        clsMailSvc = new MailMessage();

        clsMailSvc.From = new MailAddress(strFrom);
        if (strTo != "")
        {
            string[] str = strTo.Split(';');
            for (int i = 0; i < str.Length; i++)
            {
                if (str.GetValue(i).ToString() != null && str.GetValue(i).ToString().Trim() != "")
                    clsMailSvc.To.Add(new MailAddress(str.GetValue(i).ToString()));
            }
        }
        clsMailSvc.Subject = strSubject;
      
        if (strCc != "")
        {
            string[] str = strCc.Split(';');
            for (int i = 0; i < str.Length; i++)
            {
                if (str.GetValue(i).ToString() != null && str.GetValue(i).ToString().Trim() != "")

                    clsMailSvc.CC.Add(new MailAddress(str.GetValue(i).ToString()));
            }
        }
        if (strBcc != "")
        {
            string[] str = strBcc.Split(';');
            for (int i = 0; i < str.Length; i++)
            {
                if (str.GetValue(i).ToString() != null && str.GetValue(i).ToString().Trim() != "")
                    clsMailSvc.Bcc.Add(new MailAddress(str.GetValue(i).ToString()));
            }
        }

        if (attFile != null)
        {
            foreach (string f in attFile)
                clsMailSvc.Attachments.Add(new Attachment(f));
        }

        clsMailSvc.Body = strBody;
        clsMailSvc.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
        clsMailSvc.IsBodyHtml = true;
        clsMailSvc.Priority = MailPriority;

        System.Net.Mail.SmtpClient clsSmtpClient = new SmtpClient(SCC.AppSettings["MailServer"].Trim());
        try
        {
            clsSmtpClient.Send(clsMailSvc);
        }
        catch (Exception ex)
        {
            //throw ex.Message;
            Console.Write(ex.Message);
        }
        finally
        {
            clsMailSvc.Attachments.Dispose();
            clsMailSvc.Dispose();
        }
    }

原文地址:https://www.cnblogs.com/80028366local/p/12775143.html