using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Utility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.AccessControl;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
namespace Kingo.PluginServiceInterface
{
    /// 
    /// 公共插件-公共方法
    /// 
    public static class CommonHelper
    {
        [System.Runtime.InteropServices.DllImport("winInet.dll")]
        private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved);
        /// 
        /// 判断本机是否联网
        /// 
        /// 
        public static bool IsConnectNetwork()
        {
            try
            {
                //return false;
                int dwFlag = 0;
                //false表示没有连接到任何网络,true表示已连接到网络上
                if (!InternetGetConnectedState(ref dwFlag, 0))
                {
                    //if (!InternetGetConnectedState(ref dwFlag, 0))
                    //     Console.WriteLine("未连网!");
                    //else if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
                    //    Console.WriteLine("采用调治解调器上网。");
                    //else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
                    //    Console.WriteLine("采用网卡上网。");
                    return false;
                }
                Task task = new System.Threading.Tasks.TaskFactory().StartNew(() =>
                {
                    //判断当前网络是否可用
                    IPAddress[] addresslist = Dns.GetHostAddresses("www.baidu.com");
                    if (addresslist[0].ToString().Length <= 6)//未联网
                    {
                        return false;
                    }
                    else//联网
                    {
                        return true;
                    }
                    //ping方法判断是否联网
                    //System.Net.NetworkInformation.Ping a = new System.Net.NetworkInformation.Ping();
                    //System.Net.NetworkInformation.PingReply re = a.Send("www.baidu.com", 10);
                    //return (re.Status == System.Net.NetworkInformation.IPStatus.Success);
                });
                /*
                 * 此处等待100毫秒是因为:有些局域网、政务网(广东省政务网)ping百度网站时一直不返回,
                 * 所以是等待100毫秒如果不返回就当做是未联网状态,
                 * 注意:等待时间不能过长,因为当前软件有定时器(每秒调用一次)监测联网状态,会一直监测网络状态调用此方法,等待时间过长会导致线程阻塞。
                 */
                if (task.Wait(100))//在分配的时间(100毫秒)内完成执行
                {
                    return task.Result;
                }
                else//超过100毫秒未返回,则当做是未联网状态
                {
                    return false;
                }
            }
            catch //(Exception ex)
            {
                //LogAPI.Debug("判断本机器是否联网异常:" + ex.Message);
                return false;
            }
        }
        /// 
        /// 对象深拷贝
        /// 
        /// 
        /// 
        /// 
        public static T DeepCopyByBin(T obj)
        {
            object retval;
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                //序列化成流
                bf.Serialize(ms, obj);
                ms.Seek(0, SeekOrigin.Begin);
                //反序列化成对象
                retval = bf.Deserialize(ms);
                ms.Close();
            }
            return (T)retval;
        }
        /// 
        /// 复制或剪切文件到剪切板
        /// 
        /// 文件路径数组
        /// true:剪切;false:复制
        public static void CopyToClipboard(object obj, bool cut = false, EnumCopyType enumCopyType = EnumCopyType.enumText)
        {
            try
            {
                if (obj == null || string.IsNullOrWhiteSpace(obj.ToString()))
                {
                    return;
                }
                IDataObject data = null;
                switch (enumCopyType)
                {
                    case EnumCopyType.enumText:
                        data = new DataObject(DataFormats.Text, obj.ToString()) as IDataObject;
                        break;
                    case EnumCopyType.enumFiles:
                        data = new DataObject(DataFormats.FileDrop, obj) as IDataObject;
                        break;
                }
                System.IO.MemoryStream memo = new System.IO.MemoryStream(4);
                byte[] bytes = new byte[] { (byte)(cut ? 2 : 5), 0, 0, 0 };
                memo.Write(bytes, 0, bytes.Length);
                data.SetData("PreferredDropEffect", memo);
                Clipboard.SetDataObject(data, false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #region 文件处理
        /// 
        /// 文件夹复制
        /// 
        /// 原文件夹
        /// 目标目录
        /// 是否成功复制
        public static bool DirectoryCopy(string sourceDir, string targetDirPath)
        {
            try
            {
                if (!System.IO.Directory.Exists(sourceDir))
                {
                    return false;
                }
                string targetDir = targetDirPath + "\\" + System.IO.Path.GetFileName(sourceDir);
                if (!System.IO.Directory.Exists(targetDir))
                {
                    System.IO.Directory.CreateDirectory(targetDir);
                }
                // 文件及文件夹名称数组
                string[] dirColl = System.IO.Directory.GetDirectories(sourceDir);
                string[] fileColl = System.IO.Directory.GetFiles(sourceDir);
                // 便利所有文件
                if (fileColl.Length > 0)
                {
                    string fileName;
                    foreach (string fileDir in fileColl)
                    {
                        fileName = System.IO.Path.GetFileName(fileDir);
                        System.IO.File.Copy(sourceDir + "\\" + fileName, targetDir + "\\" + fileName, true);
                    }
                }
                // 遍历所有文件夹
                if (dirColl.Length > 0)
                {
                    string folderName;
                    foreach (string dir in dirColl)
                    {
                        folderName = System.IO.Path.GetFileName(dir);
                        // 递归调用
                        System.IO.Directory.CreateDirectory(targetDir + "\\" + folderName);
                        DirectoryCopy(dir, targetDir + "\\" + folderName);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// 
        /// 清空文件夹(文件占用不处理)
        /// 
        /// 
        public static void DelectDir(string srcPath)
        {
            try
            {
                if (!Directory.Exists(srcPath))
                    Directory.CreateDirectory(srcPath);
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception)
            { }
        }
        /// 
        /// 设置文件夹以及文件夹下文件为只读或非只读
        /// 
        /// 
        public static void SetFolderReadOnly(string folderPath, bool readOnly = true)
        {
            try
            {
                SetSubFolderReadOnly(folderPath, readOnly);
            }
            catch (Exception ex)
            {
                LogAPI.Debug("设置文件夹以及文件夹下文件为只读或非只读" + ex);
                throw ex;
            }
        }
        /// 
        /// 递归设置文件夹及文件夹下所有文件权限
        /// 
        /// 
        /// 
        private static void SetSubFolderReadOnly(string folderPath, bool readOnly = true)
        {
            try
            {
                System.IO.DirectoryInfo DirInfo = new DirectoryInfo(folderPath);
                System.IO.DirectoryInfo[] directoryInfos = DirInfo.GetDirectories();
                if (directoryInfos != null && directoryInfos.Length > 0)
                {
                    foreach (var item in directoryInfos)
                    {
                        SetSubFolderReadOnly(item.FullName, readOnly);
                    }
                }
                FileInfo[] fileInfos = DirInfo.GetFiles();
                if (fileInfos != null && fileInfos.Length > 0)
                {
                    foreach (var item in fileInfos)
                    {
                        SetFileReadAccess(item.FullName, readOnly);
                    }
                }
                if (readOnly)
                {
                    DirInfo.Attributes = FileAttributes.ReadOnly & FileAttributes.Directory;
                }
                else
                {
                    DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// 
        /// 设置文件只读或非只读
        /// 
        /// 
        /// 
        public static void SetFileReadAccess(string FileName, bool SetReadOnly = true) //注意这个函数
        {
            try
            {
                FileInfo fInfo = new FileInfo(FileName);
                if (fInfo.IsReadOnly != SetReadOnly)
                {
                    fInfo.IsReadOnly = SetReadOnly;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("设置文件只读异常:" + ex.Message);
            }
        }
        /// 
        /// 读取text文件内容
        /// 
        /// 文件路径
        /// 
        public static string ReadTextFileConten(string FilePath)
        {
            string content = string.Empty;
            try
            {
                // 创建一个 StreamReader 的实例来读取文件 
                // using 语句也能关闭 StreamReader
                using (StreamReader sr = new StreamReader(FilePath))
                {
                    string line;
                    // 从文件读取并显示行,直到文件的末尾 
                    while ((line = sr.ReadLine()) != null)
                    {
                        content += line;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return content;
        }
        /// 
        /// 拷贝模板gdb文件夹
        /// 
        /// 
        /// 
        /// 
        public static void CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
        {
            try
            {
                SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
                DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
                if (Directory.Exists(SourcePath))
                {
                    if (Directory.Exists(DestinationPath) == false)
                        Directory.CreateDirectory(DestinationPath);
                    foreach (string fls in Directory.GetFiles(SourcePath))
                    {
                        FileInfo flinfo = new FileInfo(fls);
                        flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
                    }
                    foreach (string drs in Directory.GetDirectories(SourcePath))
                    {
                        DirectoryInfo drinfo = new DirectoryInfo(drs);
                        CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        /// 
        /// 执行压缩SQLite数据库
        /// 
        /// 压缩数据库db路径
        public static void ExecuteZip(string dbPath)
        {
            IRDBHelper rdbHelper = null;
            try
            {
                rdbHelper = RDBFactory.CreateDbHelper($"{dbPath}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
                rdbHelper.ExecuteNonQueryWithException("VACUUM", System.Data.CommandType.Text);
            }
            catch (Exception ex)
            {
                throw new Exception("输出成果压缩db异常:" + ex.Message);
            }
            finally
            {
                if (rdbHelper != null)
                {
                    rdbHelper.DisConnect();
                }
            }
        }
        /// 
        /// 从UserLoginConfig.xml中获取指定key的值
        /// 
        /// 
        /// 
        public static string GetAppsetingValueByKey(string key)
        {
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                string strPath = SysAppPath.GetConfigPath() + "UserLoginConfig.xml";
                doc.Load(strPath);
                System.Xml.XmlNode xmlSysNode = doc.SelectSingleNode("configuration/AppSettings");
                if (xmlSysNode.ChildNodes != null && xmlSysNode.ChildNodes.Count > 0)
                {
                    foreach (System.Xml.XmlNode node in xmlSysNode.ChildNodes)
                    {
                        if (node.Attributes["Key"].Value == key)
                        {
                            return node.Attributes["Value"].Value;
                        }
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return "";
            }
        }
        /// 
        /// 更新配置文件UserLoginConfig.xml值
        /// 
        /// 
        /// 
        /// 
        public static void UpdateAppsettingValueByKey(string key, string value, string XMLName)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                string strPath = SysAppPath.GetConfigPath() + $"{XMLName.Trim()}.xml";
                doc.Load(strPath);
                XmlNode xmlSysNode = doc.SelectSingleNode("configuration/AppSettings");
                if (xmlSysNode.ChildNodes != null && xmlSysNode.ChildNodes.Count > 0)
                {
                    foreach (XmlNode node in xmlSysNode.ChildNodes)
                    {
                        if (node.Attributes["Key"].Value == key)
                        {
                            node.Attributes["Value"].Value = value;
                            doc.Save(strPath);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// 
        /// 执行地图工具
        /// 
        /// 执行功能名
        public static void ExeCommandOperation(string HandleName)
        {
            string CommandID = string.Empty;
            string BundleSymbolicName = string.Empty;
            switch (HandleName)
            {
                case "执行结束编辑":
                    CommandID = "Kingo.Plugin.EngineEditor.Commands.Commands.ControlsStopEditToolCommand";
                    BundleSymbolicName = "Kingo.Plugin.EngineEditor";
                    break;
                case "执行全图":
                    CommandID = "Kingo.Plugin.MapView.Commands.ControlsMapFullExtent";
                    BundleSymbolicName = "Kingo.Plugin.MapView";
                    break;
                case "执行数据解压":
                    CommandID = "Kingo.Plugin.DTBJK.Commands.CmdDecompressionDB";
                    BundleSymbolicName = "Kingo.Plugin.DTBJK";
                    break;
                case "创建变更数据库":
                    CommandID = "Kingo.Plugin.BGSetting.Commands.CmdCreateBGDB";
                    BundleSymbolicName = "Kingo.Plugin.BGSetting";
                    break;
                default:
                    break;
            }
            ExeCommandIDByBundle(CommandID, BundleSymbolicName);
        }
        /// 
        /// 执行已执行插件的配置功能(无参)
        /// 
        /// 例如:Kingo.Plugin.MapView.Commands.CmdSaveProject
        /// 例如:Kingo.Plugin.MapView
        private static void ExeCommandIDByBundle(string CommandID, string BundleSymbolicName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(CommandID) || string.IsNullOrWhiteSpace(BundleSymbolicName) || UIShell.OSGi.BundleRuntime.Instance == null)
                    return;
                var bundle = UIShell.OSGi.BundleRuntime.Instance.Framework.Bundles.Find(x => x.SymbolicName.Equals(BundleSymbolicName));
                if (bundle == null) return;
                KGIS.Framework.Commands.ICommandManager _CmdManager = UIShell.OSGi.BundleRuntime.Instance.GetFirstOrDefaultService();
                if (_CmdManager != null)
                {
                    var pCmd = _CmdManager.AddCmd(CommandID, bundle, null);
                    if (pCmd is BaseMapMenuCommand)
                        KGIS.Framework.Menus.ServicesInvokes.CommandManagerInvoke.ExeCommand(pCmd, null);
                    if (pCmd is ESRI.ArcGIS.SystemUI.ICommand)
                        (pCmd as ESRI.ArcGIS.SystemUI.ICommand).OnClick();
                    else if (pCmd is KGIS.Framework.Commands.IMenuCommand)
                        (pCmd as KGIS.Framework.Commands.IMenuCommand).OnClick();
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("执行已执行插件的配置功能失败:" + ex);
                throw ex;
            }
        }
        public static void InsertSQLiteData(string dbPath, List sqlList)
        {
            try
            {
                using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + dbPath))
                {
                    conn.Open();
                    using (SQLiteTransaction pTrans = conn.BeginTransaction())
                    {
                        using (SQLiteCommand cmd = new SQLiteCommand(conn))
                        {
                            for (int i = 0; i < sqlList.Count(); i++)
                            {
                                cmd.CommandText = sqlList[i];
                                cmd.ExecuteNonQuery();
                            }
                            pTrans.Commit();
                        }
                    }
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("批量插入SQLite数据(地址:" + dbPath + ") 执行失败,异常原因: " + ex.Message + " ; ");
                return;
            }
        }
        /// 
        /// 记录错误日志信息
        /// 
        /// 
        /// 
        public static void RecordsErrLog(string LogInfo, Exception ex)
        {
            LogAPI.Debug($"{LogInfo},异常信息如下所示:");
            LogAPI.Debug($"**************************");
            LogAPI.Debug($"{ex}");
            LogAPI.Debug($"**************************");
            LogAPI.Debug($"{LogInfo},异常信息结束!:");
        }
        public static string CreateTempDB(string pType, string pSubType = "")
        {
            string result = string.Empty;
            try
            {
                string dbPath = Path.Combine(Directory.GetCurrentDirectory(), "Temp" + ".db");
                string gdbFolder = Directory.GetCurrentDirectory() + "\\Temp\\" + pType;
                if (!Directory.Exists(gdbFolder))
                    Directory.CreateDirectory(gdbFolder);
                try
                {
                    DelectDir(gdbFolder);
                }
                catch
                {
                    //删除临时数据异常 不做处理 
                }
                string gdbFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string path = System.IO.Path.Combine(gdbFolder, string.IsNullOrWhiteSpace(pSubType) ? gdbFileName : pSubType);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string savePath = Path.Combine(path, "TempGDB.gdb");
                string templeteGDBPath = Path.Combine(SysAppPath.GetCurrentAppPath(), "Template", "TempGDB.gdb");
                CopyDirectory(templeteGDBPath, savePath, true);
                if (File.Exists(dbPath))
                {
                    File.Copy(dbPath, Path.Combine(path, "Temp" + ".sqlite"));
                }
                else
                {
                    Console.WriteLine(string.Format("文件{0}不存在!", dbPath));
                }
                result = path;
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建临时数据库失败!" + ex.Message);
                throw ex;
            }
            return result;
        }
        #region CreateTempGDB
        /// 
        /// 创建临时GDB文件
        /// 
        /// 自定义数据库名称
        /// 指定目录名称
        /// 
        public static string CreateTempGDB(string DefinedName, string SpecifiedPath)
        {
            try
            {
                string gdbFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string resultPath = Path.Combine(SpecifiedPath, gdbFileName);
                if (!Directory.Exists(resultPath))
                    Directory.CreateDirectory(resultPath);
                string savePath = Path.Combine(resultPath, $"{DefinedName}.gdb");
                string templeteGDBPath = Path.Combine(SysAppPath.GetCurrentAppPath(), "Template", "TempGDB.gdb");
                CopyDirectory(templeteGDBPath, savePath, true);
                return savePath;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("创建临时GDB文件异常:" + ex.Message + ex.StackTrace);
                throw ex;
            }
        }
        /// 
        /// 创建临时GDB文件
        /// 
        /// 自定义数据库上级目录名称
        /// 
        public static string CreateTempGDB(string DefinedPath, ref string DefinedPathDir)
        {
            string savePath;
            try
            {
                string gdbFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string resultPath = Path.Combine(SysAppPath.GetCurrentAppPath(), $"Temp\\{DefinedPath}", gdbFileName);
                if (!Directory.Exists(resultPath))
                    Directory.CreateDirectory(resultPath);
                DefinedPathDir = resultPath;
                if (Directory.Exists(Path.Combine(SysAppPath.GetCurrentAppPath(), $"Temp\\{DefinedPath}")))
                    DelectDir(Path.Combine(SysAppPath.GetCurrentAppPath(), $"Temp\\{DefinedPath}"));
                savePath = Path.Combine(resultPath, "TempGDB.gdb");
                string templeteGDBPath = Path.Combine(SysAppPath.GetCurrentAppPath(), "Template", "TempGDB.gdb");
                CopyDirectory(templeteGDBPath, savePath, true);
            }
            catch (Exception ex)
            {
                LogAPI.Debug("创建临时GDB文件异常:" + ex.Message + ex.StackTrace);
                throw ex;
            }
            return savePath;
        }
        public static string CreateTempGDB(string DefinedPath)
        {
            string savePath = string.Empty;
            try
            {
                string gdbFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string resultPath = Path.Combine(SysAppPath.GetCurrentAppPath(), $"Temp\\{DefinedPath}", gdbFileName);
                if (!Directory.Exists(resultPath))
                    Directory.CreateDirectory(resultPath);
                if (Directory.Exists(Path.Combine(SysAppPath.GetCurrentAppPath(), $"Temp\\{DefinedPath}")))
                    DelectDir(Path.Combine(SysAppPath.GetCurrentAppPath(), $"Temp\\{DefinedPath}"));
                savePath = Path.Combine(resultPath, "TempGDB.gdb");
                string templeteGDBPath = Path.Combine(SysAppPath.GetCurrentAppPath(), "Template", "TempGDB.gdb");
                CopyDirectory(templeteGDBPath, savePath, true);
            }
            catch (Exception ex)
            {
                LogAPI.Debug("创建临时GDB文件异常:" + ex.Message + ex.StackTrace);
                throw ex;
            }
            return savePath;
        }
        #endregion
        /// 
        /// 区划代码_名称(330110_余杭区)
        /// 
        /// 
        public static string GetXZQCode_Name(string TempBSMCode)
        {
            IRDBHelper rdbHelper = null;
            try
            {
                string systemPath = SysAppPath.GetDataBasePath() + "System.mdb";
                if (File.Exists(systemPath))
                {
                    string connStr = ConfigurationManager.AppSettings.Get("MDBOledbConnection");// SysConfigsOprator.GetDBConnectionByName("MDBOledbConnection");
                    connStr = string.Format(connStr, systemPath);
                    rdbHelper = RDBFactory.CreateDbHelper(connStr, DatabaseType.MSAccess);
                    string strPrWhere = "1=2";
                    string strWhere = string.Empty;
                    strWhere += string.Format(" or XZQ LIKE '{0}%'", TempBSMCode.Substring(0, 6));
                    if (!string.IsNullOrWhiteSpace(strWhere))
                        strWhere = strPrWhere + strWhere;
                    else
                        strWhere = "1=1";
                    string strSQL = "select OBJECTID AS ID, XZQ AS CODE,XZQMC AS NAME from XZQ Where " + strWhere + "";
                    LogAPI.Debug(strWhere);
                    DataTable dt = rdbHelper.ExecuteDatatable("Dic", strSQL, true);
                    if (dt != null)
                    {
                        List xzqCoderesult = TBToList.ToList(dt);
                        foreach (var item in xzqCoderesult)
                        {
                            return item.CODE + "_" + item.NAME;
                        }
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
                return "";
            }
            finally
            {
                rdbHelper?.DisConnect();
            }
        }
        /// 
        ///为文件夹添加users,everyone,Administrator用户组的完全控制权限
        /// 
        /// 
        public static void AddSecurityControll2Folder(string dirPath)
        {
            //获取文件夹信息
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            //获得该文件夹的所有访问权限
            System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
            //设定文件ACL继承
            InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            //添加ereryone用户组的访问权限规则 完全控制权限
            FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            //添加Users用户组的访问权限规则 完全控制权限
            FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            //添加Administrator用户组的访问权限规则 完全控制权限
            FileSystemAccessRule AdministratorFileSystemAccessRule = new FileSystemAccessRule("Administrator", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            bool isModified = false;
            dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
            dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
            //设置访问权限
            dir.SetAccessControl(dirSecurity);
        }
    }
    public enum EnumCopyType
    {
        enumText = 1,
        enumFiles = 2
    }
}