远程磁盘清理

来源:互联网 发布:淘宝详情免费视频 编辑:程序博客网 时间:2024/06/11 17:02

    /// <summary>
    /// 远程/ 本地自动清理
    /// </summary>
    public class RemoteAutoCleaning : BackGroundBase
    {
        #region 变量定义

        OAFLIBSystem oaflibSystem = new OAFLIBSystem ();
        string strMsg = "";
        ArrayList FileList = new ArrayList();
        string ip = "";
        string filetype = "";
        int holdtime = 7;

        #endregion

        public void ThreadRun( TabPageBase tabPageBase , ThreadProvider threadProvider)
        {
            strMsg = "";
            tabPageBase.WriteInfo (" 正在开始运行自动清理程序 ");
            tabPageBase.WriteInfo (" 正在获取需要清理的目录信息 ");

            string strHostName = Dns .GetHostName (); // 取得本机的主机名
            IPHostEntry ipEntry = Dns .GetHostByName (strHostName ); // 取得本机IP
            string localip = ipEntry. AddressList[0].ToString (); // 假设本地主机为单网卡,取得第一个 IP

            string username = "111";//"Administrator";
            string password = "111";//"password";

            DataSet ds = new DataSet();
            ParmArray parmArray = new ParmArray();
            ds = oaflibSystem.GetRemoteAutoCleaningIP (parmArray );
            if (! OperateUI. HaveData( ds))
            {
                tabPageBase.WriteError (" 未设置需要清理的电脑 IP");
                return;
            }

            #region 循环遍历 IP目录

            foreach ( DataRow dr in ds. Tables[0]. Rows)
            {
                try
                {
                    ip = dr[ "TBRS"].ToString ().Trim ();
                    filetype= "";
                    holdtime = 7;
                    string strpath = dr[ "TBDTL1"].ToString ().Trim ();
                    string strdisk = strpath. Substring(0,2);
                    string strlist = "\\\\" + strpath .Substring (3, strpath.Length - 3).Replace (@"\" , @"\\" ) + "\\\\%" ;

                    if ( dr[ "TBDTL2"].ToString ().Trim ()!="" )
                    {
                        filetype = dr[ "TBDTL2"].ToString ().Trim (); // 文件类型
                    }
                    if ( dr[ "TBDTL4"].ToString ().Trim ()!="0" )
                      {
                        holdtime = int.Parse (dr ["TBDTL4" ].ToString ().Trim ()); // 保留时间
                      }
                    tabPageBase.WriteInfo (" 正在清理的电脑 IP " + ip+ "下的目录" +strpath );
                    if ( ip == localip)
                    {
                        #region 本地

                        DirectoryInfo d = new DirectoryInfo (strpath );
                        FileList. Clear();
                        ArrayList Flst = GetAllFile( d);
                        for ( int i = 0; i < Flst. Count; i++)
                        {
                            tabPageBase.WriteError (Flst [i ].ToString ().Trim ());
                        }

                        #endregion
                    }
                    else
                    {
                        #region 远程

                        bool filecheck = false;
                        ConnectionOptions connectionOptions = new ConnectionOptions();
                        connectionOptions.Username = username ;
                        connectionOptions.Password = password ;
                        connectionOptions.Timeout = new TimeSpan (1, 1, 1, 1);//连接时间

                        //ManagementScope 的服务器和命名空间。
                        string path = string.Format ("\\\\{0}\\root\\cimv2" , ip );
                        ManagementScope scope = new ManagementScope(path , connectionOptions );
                        scope. Connect();

                        //验证目录是否配置错误
                        string strQuerys = string. Format( "select * from CIM_DataFile where (Extension='dll' or Extension='exe') and Drive = '{0}' and Path like '{1}'", strdisk, strlist);
                        ObjectQuery querys = new ObjectQuery (strQuerys );
                        ManagementObjectSearcher searchers = new ManagementObjectSearcher(scope ,querys );
                        foreach ( ManagementObject ms in searchers .Get ())
                        {
                            strMsg += ip + "  " + strpath + " 目录中含有dll,.exe等文件时,可能是配置错误,无法删除此目录下的文件 " + System.Environment .NewLine ;
                            tabPageBase.WriteError (ip + "  " + strpath + "目录中含有dll,.exe 等文件时,可能是配置错误,无法删除此目录下的文件 ");
                            filecheck = true;
                            break;
                        }
                        if ( filecheck)
                        {
                            continue;
                        }

                        //查询目录下的文件信息
                        string strQuery = string. Format( "select * from CIM_DataFile where Drive = '{0}' and Path like '{1}'", strdisk, strlist);
                        ObjectQuery query = new ObjectQuery (strQuery );
                        ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope , query );
                        foreach ( ManagementObject m in searcher .Get ())
                        {
                            string s = m["Name" ].ToString ().Trim ().ToUpper ();
                            string str = m["CreationDate" ].ToString ().Trim ().Substring (0, 8);

                            IFormatProvider ifp = new CultureInfo("zh-CN" , true );
                            DateTime dt = DateTime. ParseExact( str, "yyyyMMdd", ifp );

                            if (! isintimerange(holdtime , dt ))
                            {
                                if ( filetype != "")
                                {
                                    if ( s. EndsWith( "." + filetype ))
                                    {
                                        m. Delete();
                                    }
                                }
                                else
                                {
                                    m. Delete();
                                }
                            }
                        }

                        #endregion
                    }
                }
                catch ( Exception e)
                {}
            }

            #endregion

            #region 遍历邮件目录发送

            if ( strMsg != "")
            {
                parmArray. Clear();
                ds = oaflibSystem.GetRemoteEmailAddress (parmArray );
                foreach ( DataRow dr in ds. Tables[0]. Rows)
                {
                    string tomailaddress = dr["TBRS" ].ToString ().Trim ().ToLower ();
                    sendEmail( tomailaddress, strMsg );
                }
            } 

            #endregion
        }

        #region 搜索文件夹中的文件 (本地 )

        ArrayList GetAllFile( DirectoryInfo dir)
        {
            FileInfo[] allFile = dir. GetFiles();
            foreach ( FileInfo fi in allFile)
            {
                string filename = fi.Name .ToString ().Trim ().ToString ().ToUpper ();
                DateTime creationtime = fi .CreationTime ;
                if (! isintimerange(holdtime , creationtime ))
                {
                    if ( filename. EndsWith( ".DLL") || filename.EndsWith (".EXE" ))
                    {
                        FileList. Add( ip + "  " + fi .DirectoryName + " 目录中含有dll,.exe等文件时,可能是配置错误,无法删除 ");
                        strMsg += ip + "  " + fi .DirectoryName + " 目录中含有dll,.exe等文件时,可能是配置错误,无法删除 " + System.Environment .NewLine ;
                        break;
                    }
                    else
                    {
                        if ( filetype != "")
                        {
                            if ( fi. Name. EndsWith( "."+filetype ))
                            {
                                fi. Delete();
                            }
                        }
                        else
                        {
                            fi. Delete();                       
                        }
                    }
                }
            }

            DirectoryInfo[] allDir = dir .GetDirectories ();
            foreach ( DirectoryInfo d in allDir )
            {
                GetAllFile( d);
            }
            return FileList;
        }

        #endregion

        #region 是否在时间范围内

        private bool isintimerange(int timerange , DateTime creattime )
        {
            DateTime currenttime = DateTime .Now ;
            TimeSpan distime = currenttime.Subtract (creattime );
            if ( distime. TotalDays. CompareTo( Convert. ToDouble( timerange)) > 0) //默认设置天
            {
                return false;
            }
            return true;
        }

        #endregion

        #region 统一发送 E-Mail

        private void sendEmail( string toMail, string mailText)
        {
            PENSendMail mail = new PENSendMail("111@penavicoxm.com" , toMail , "" , "" , " 文件自动清理监控报告 ", mailText);
            mail. send();
        }

        #endregion
    }
0 0
原创粉丝点击