private XmlDocument ReadXml()
        {
            XmlDocument doc1 = new XmlDocument();

            try
            {
                if (File.Exists(AppConfig.WebEnhanceMenusDic))
                {
                    doc1.LoadXml(File.ReadAllText(AppConfig.WebEnhanceMenusDic, EncodingType.GetType(AppConfig.WebEnhanceMenusDic)));
                }
                else
                {
                    doc1.LoadXml(Properties.Resources.EnhanceMenusDic);
                }
                if (File.Exists(AppConfig.UserEnhanceMenusDic))
                {
                    XmlDocument doc2 = new XmlDocument();
                    doc2.LoadXml(File.ReadAllText(AppConfig.UserEnhanceMenusDic, EncodingType.GetType(AppConfig.UserEnhanceMenusDic)));
                    foreach (XmlNode xn in doc2.DocumentElement.ChildNodes)
                    {
                        XmlNode node = doc1.ImportNode(xn, true);
                        doc1.DocumentElement.AppendChild(node);
                    }
                }
            }
            catch { }
            return(doc1);
        }
示例#2
0
 private void button6_Click(object sender, EventArgs e)
 {
     try
     {
         var    reg    = new Regex("[\u4e00-\u9fa5?]+__1");
         string str    = File.ReadAllText(textBox3.Text, EncodingType.GetType(openFileDialog1.FileName));
         var    str_en = str;
         var    str_es = str;
         var    str_vn = str;
         var    arr    = reg.Matches(str);
         foreach (Match v in arr)
         {
             var txt = v.Value.Replace("__1", "");
             var sql = "select name_en,name_es,name_vn from a_trans where name_cn='" + txt + "'";
             var dt  = DBHelper.GetMany(sql);
             if (dt.Rows.Count > 0)
             {
                 var txt_en = dt.Rows[0]["name_en"].ToString();
                 var txt_es = dt.Rows[0]["name_es"].ToString();
                 var txt_vn = dt.Rows[0]["name_vn"].ToString();
                 str_en = str_en.Replace(v.Value, txt_en);
                 str_es = str_es.Replace(v.Value, txt_es);
                 str_vn = str_vn.Replace(v.Value, txt_vn);
             }
         }
         File.WriteAllText(openFileDialog1.FileName + ".en.asp", str_en, Encoding.UTF8);
         File.WriteAllText(openFileDialog1.FileName + ".es.asp", str_es, Encoding.UTF8);
         File.WriteAllText(openFileDialog1.FileName + ".vn.asp", str_vn, Encoding.UTF8);
         MessageBox.Show("修改成功!");
     }
     catch (Exception ex)
     {
         MessageBox.Show("修改失败!" + ex.Message);
     }
 }
示例#3
0
        public void GetHtmlContent()
        {
            string        filePath    = Path.Combine(testFolder, "Index.cshtml");
            var           encoding    = EncodingType.GetType(filePath);
            string        fileContent = File.ReadAllText(filePath, encoding);
            var           matches     = Regex.Matches(fileContent, "L\\(['\"]{1}([^;\\)]+)['\"]{1}\\)", RegexOptions.Multiline);
            List <string> matchValues = new List <string>();

            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    if (match.Groups.Count > 0)
                    {
                        string lastValue = match.Groups[1].Value;
                        matchValues.Add(lastValue);
                    }
                    else
                    {
                        matchValues.Add(match.Value);
                    }
                }
            }
            Assert.AreEqual(matches.Count, 2);
        }
        public static XmlDocument ReadXml(string webDicPath, string userDicPath, string appDic)
        {
            XmlDocument doc1 = new XmlDocument();

            try
            {
                if (File.Exists(webDicPath))
                {
                    doc1.LoadXml(File.ReadAllText(webDicPath, EncodingType.GetType(webDicPath)));
                }
                else
                {
                    doc1.LoadXml(appDic);
                }
                if (File.Exists(userDicPath))
                {
                    XmlDocument doc2 = new XmlDocument();
                    doc2.LoadXml(File.ReadAllText(userDicPath, EncodingType.GetType(userDicPath)));
                    foreach (XmlNode xn in doc2.DocumentElement.ChildNodes)
                    {
                        XmlNode node = doc1.ImportNode(xn, true);
                        doc1.DocumentElement.AppendChild(node);
                    }
                }
            }
            catch { }
            return(doc1);
        }
示例#5
0
        private async Task <int> Work(string filePath, string cookiePath)
        {
            string cookie = File.ReadAllText(cookiePath, EncodingType.GetType(cookiePath));

            var fileEncoding  = EncodingType.GetType(filePath);
            var fileContent   = File.ReadAllText(filePath, fileEncoding);
            var fileInfo      = new FileInfo(filePath);
            var fileExtension = fileInfo.Extension;
            var fileDir       = fileInfo.DirectoryName;

            var imgProc = new ImageProcessor();
            var imgList = imgProc.Process(fileContent);

            Console.WriteLine($"提取图片成功,共{imgList.Count}个.");

            var uploader = new ClientUploader("https://yq.aliyun.com");

            var replaceDic = new Dictionary <string, string>();

            foreach (var img in imgList)
            {
                string imgPhyPath = Path.Combine(fileDir, img);

                Console.WriteLine($"正在上传图片:{imgPhyPath}");
                try
                {
                    var res = await uploader.UploadAsync(imgPhyPath, "/upload/img2", "fileToUpload", new Dictionary <string, string>()
                    {
                        ["Cookie"] = cookie
                    });

                    //校验
                    res = res.Replace("\r\n", "");
                    if (!res.StartsWith("https://yqfile.alicdn.com"))
                    {
                        Console.WriteLine("Cookie无效!");
                        return(1);
                    }

                    replaceDic.Add(img, res);

                    Console.WriteLine("上传成功!");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"处理失败!{e.Message}");
                    return(1);
                }
            }

            var    newContent  = imgProc.Replace(replaceDic, fileContent);
            string newFileName = filePath.Substring(0, filePath.LastIndexOf('.')) + "-aliyun" + fileExtension;

            File.WriteAllText(newFileName, newContent, fileEncoding);

            Console.WriteLine($"处理完成!文件保存在:{newFileName}");

            return(0);
        }
示例#6
0
        public void TestCSharpFileContent()
        {
            //文件测试
            string filePath      = Path.Combine(testFolder, "GraphTestCase.cs");
            var    encoding      = EncodingType.GetType(filePath);
            string fileContent   = File.ReadAllText(filePath, encoding);
            string replaceString = Regex.Replace(fileContent, @"^\s*//[^/]{1}[\s\S]*?$\n", "", RegexOptions.Multiline);

            Assert.AreNotEqual(replaceString, fileContent);
        }
示例#7
0
        /// <summary>
        /// 自动识别UTF-8或者GBK编码的文件读取
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string file2text(FileInfo file)
        {
            string text = "";

            using (StreamReader sr = new StreamReader(file.FullName, EncodingType.GetType(file.FullName), true, 4096))
            {
                text = sr.ReadToEnd();
            }
            return(text);
        }
示例#8
0
 public string Read(DataFileModel dataFile)
 {
     encode = EncodingType.GetType(dataFile.Data);
     if (encode != null)
     {
         return(encode.GetString(dataFile.Data));
     }
     else
     {
         return(null);
     }
 }
        private void LoadDocItems(string xmlPath, GroupPathItem groupItem)
        {
            if (!File.Exists(xmlPath))
            {
                return;
            }
            this.AddItem(groupItem);
            XmlDocument doc = new XmlDocument();

            try { doc.LoadXml(File.ReadAllText(xmlPath, EncodingType.GetType(xmlPath)).Trim()); }
            catch (Exception e) { MessageBoxEx.Show(e.Message); return; }
            foreach (XmlNode xn in doc.DocumentElement.ChildNodes)
            {
                try
                {
                    SubGroupItem subGroupItem = GetGroupPathItem(xn);
                    if (subGroupItem == null)
                    {
                        continue;
                    }
                    this.AddItem(subGroupItem);
                    XmlElement shellXE   = (XmlElement)xn.SelectSingleNode("Shell");
                    XmlElement shellExXE = (XmlElement)xn.SelectSingleNode("ShellEx");
                    if (shellXE != null)
                    {
                        LoadShellItems(shellXE, subGroupItem);
                    }
                    if (shellExXE != null)
                    {
                        LoadShellExItems(shellExXE, subGroupItem);
                    }
                    subGroupItem.HideWhenNoSubItem();
                    subGroupItem.FoldGroupItem = groupItem;
                }
                catch { continue; }
            }
            groupItem.IsFold = true;
            groupItem.HideWhenNoSubItem();
        }
示例#10
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (File.Exists(textBox1.Text))
     {
         string str     = File.ReadAllText(textBox1.Text, EncodingType.GetType(openFileDialog1.FileName));
         var    strlist = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);
         for (int i = 0; i < strlist.Count(); i++)
         {
             var s = strlist[i];
             if (s.Trim() != "" && s.IndexOf("\t") > -1)
             {
                 var s2   = s.Split(new string[] { "\t" }, StringSplitOptions.None);
                 var sql1 = string.Format("select 1 from a_trans where name_cn = '{0}'", s2[0]);
                 if (DBHelper.GetSingle(sql1) == null)
                 {
                     var sql2 = string.Format("insert into a_trans ( name_cn, path)values('{0}','{1}')", s2[0], s2[1]);
                     DBHelper.Exec(sql2);
                 }
             }
         }
         MessageBox.Show("导入成功!");
     }
 }
示例#11
0
 private void button4_Click(object sender, EventArgs e)
 {
     if (File.Exists(textBox2.Text))
     {
         string str     = File.ReadAllText(textBox2.Text, EncodingType.GetType(openFileDialog1.FileName));
         var    strlist = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);
         for (int i = 0; i < strlist.Count(); i++)
         {
             var s = strlist[i];
             if (s.Trim() != "" && s.IndexOf("\t") > -1)
             {
                 var s2   = s.Split(new string[] { "\t" }, StringSplitOptions.None);
                 var sql1 = string.Format("select name_en from a_trans where name_cn = '{0}'", s2[0]);
                 var rs   = DBHelper.GetSingle(sql1);
                 if (rs != null)
                 {
                     var sql2 = string.Format("update a_trans set name_en=N'{0}', name_es=N'{1}', name_vn=N'{2}', flg='{4}'  where name_cn='{3}'", s2[1], s2[2], s2[3], s2[0], checkBox4.Checked ? 0 : 1);
                     DBHelper.Exec(sql2);
                 }
             }
         }
         MessageBox.Show("导入成功!");
     }
 }
示例#12
0
        public bool ExportTask(string home, string backup_dir, string log, string cmd)
        {
            bool          bSuccess = false;
            List <string> cmds     = new List <string>();

            cmds.Add(string.Format("set DM_HOME={0}", home));
            cmds.Add(@"set PATH=%path%;%DM_HOME%\bin");
            cmds.Add(cmd);
            CmdHelper.Execute(cmds.ToArray());
            var logfile = Path.Combine(backup_dir, log);

            if (File.Exists(logfile))
            {
                string text = File.ReadAllText(logfile, EncodingType.GetType(logfile));
                Console.WriteLine(text);

                string pattern = @"共导出[\s\d]+个SCHEMA";
                if (Regex.IsMatch(text, pattern))
                {
                    bSuccess = true;
                }
            }
            return(bSuccess);
        }
示例#13
0
        private void button6_Click(object sender, EventArgs e)
        {
            if (File.Exists(textBox4.Text))
            {
                string str     = File.ReadAllText(textBox4.Text, EncodingType.GetType(openFileDialog1.FileName));
                var    strlist = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);

                for (int i = 0; i < strlist.Count(); i++)
                {
                    var s = strlist[i];
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }
                    var s2 = s.Replace(@"C:\Users\zhangyaof\Desktop\qingmao\ERP原件", @"C:\Users\zhangyaof\Desktop\qingmao\ERP原件副本").Replace(@"\\qmrpt02\qingmao_test", @"C:\Users\zhangyaof\Desktop\qingmao\ERP原件副本");
                    if (!Directory.Exists(Path.GetDirectoryName(s2)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(s2));
                    }
                    File.Copy(s, s2, true);
                }
                MessageBox.Show("复制成功!");
            }
        }
示例#14
0
        public void ExecuteImport(long id)
        {
            using (var ctx = new DbMonitorEntities())
            {
                var me  = ctx.MirrorExport.Find(id);
                var dic = ctx.Dictionary.Where(d => d.DTypeCode == "OracleExport" && d.DEnable == 1).ToList();
                var sc  = ctx.SessionConnection.Find(me.SCID);

                me.MEImportStatus = "开始导入";
                me.EditingTime    = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                me.MEImportTime   = me.EditingTime;
                ctx.SaveChanges();

                List <string> cmds = new List <string>();
                //变量设置是必须的
                string directory   = dic.Where(d => d.DCode == "directory").FirstOrDefault().DName,
                       oracle_base = dic.Where(d => d.DCode == "oracle_base").FirstOrDefault().DName,
                       oracle_home = dic.Where(d => d.DCode == "oracle_home").FirstOrDefault().DName,
                       oracle_sid  = dic.Where(d => d.DCode == "oracle_sid").FirstOrDefault().DName,
                       user_local  = dic.Where(d => d.DCode == "user").FirstOrDefault().DName,
                       pwd_local   = dic.Where(d => d.DCode == "pwd").FirstOrDefault().DName;

                cmds.Add(string.Format("set ORACLE_BASE={0}", oracle_base));
                cmds.Add(string.Format("set ORACLE_HOME=%ORACLE_BASE%{0}", oracle_home));
                cmds.Add(string.Format("set ORACLE_SID={0}", oracle_sid));
                cmds.Add(@"set PATH=%path%;%ORACLE_HOME%\bin");

                string file = me.MEFileName, implog = me.MELogFile.Replace(".log", "") + "_imp.log";
                //使用StringBuilder注意参数之间的空格
                StringBuilder sbExp = new StringBuilder();
                sbExp.AppendFormat("%ORACLE_HOME%\\bin\\impdp {0}/{1} directory={2} dumpfile={3} logfile={4}",
                                   user_local, pwd_local, directory, file, implog);

                cmds.Add(sbExp.ToString());
                CmdHelper.Execute(cmds.ToArray());

                var backup_dir = dic.Where(d => d.DCode == "backup_dir").FirstOrDefault().DName;
                var logfile    = Path.Combine(backup_dir, implog);
                me.MEImportLogFile = implog;

                bool bOK = false;
                if (File.Exists(logfile))
                {
                    string text = File.ReadAllText(logfile, EncodingType.GetType(logfile));

                    string pattern = @"作业[\s\S]+完成";

                    if (Regex.IsMatch(text, pattern))
                    {
                        bOK = true;
                    }
                }
                if (bOK)
                {
                    me.MEImportStatus = "导入成功";
                    me.EditingTime    = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    ctx.SaveChanges();
                }
                else
                {
                    me.MEImportStatus = "导入失败";
                    me.EditingTime    = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    ctx.SaveChanges();
                }
            }
        }
示例#15
0
        static void ProcessFile(string[] args)
        {
            try
            {
                _filePath = args[0];
                if (!File.Exists(_filePath))
                {
                    Console.WriteLine("指定的文件不存在!");
                }
                else
                {
                    _fileDir     = new FileInfo(_filePath).DirectoryName;
                    _fileContent = File.ReadAllText(_filePath);
                    var imgProcessor = new ImageProcessor();
                    var imgList      = imgProcessor.Process(_fileContent);
                    Console.WriteLine($"提取图片成功,共{imgList.Count}个.");

                    //循环上传图片
                    foreach (var img in imgList)
                    {
                        if (img.StartsWith("http"))
                        {
                            Console.WriteLine($"{img} 跳过.");
                            continue;
                        }

                        try
                        {
                            string imgPhyPath = Path.Combine(_fileDir, img);
                            if (File.Exists(imgPhyPath))
                            {
                                var imgUrl = ImageUploader.Upload(imgPhyPath);
                                if (!ReplaceDic.ContainsKey(img))
                                {
                                    ReplaceDic.Add(img, imgUrl);
                                }
                                Console.WriteLine($"{img} 上传成功. {imgUrl}");
                            }
                            else
                            {
                                Console.WriteLine($"{img} 未发现文件.");
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }

                    //替换
                    foreach (var key in ReplaceDic.Keys)
                    {
                        _fileContent = _fileContent.Replace(key, ReplaceDic[key]);
                    }

                    string newFileName = _filePath.Substring(0, _filePath.LastIndexOf('.')) + "-cnblog" +
                                         new FileInfo(_filePath).Extension;
                    File.WriteAllText(newFileName, _fileContent, EncodingType.GetType(_filePath));

                    Console.WriteLine($"处理完成!文件保存在:{newFileName}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
示例#16
0
        /// <summary>重新加载字典</summary>
        public static void ReloadDics()
        {
            XmlDocument LoadXml(string xmlPath)
            {
                if (!File.Exists(xmlPath))
                {
                    return(null);
                }
                try
                {
                    XmlDocument doc      = new XmlDocument();
                    Encoding    encoding = EncodingType.GetType(xmlPath);
                    string      xml      = File.ReadAllText(xmlPath, encoding).Trim();
                    doc.LoadXml(xml);
                    return(doc);
                }
                catch (Exception e)
                {
                    AppMessageBox.Show(e.Message + "\n" + xmlPath);
                    return(null);
                }
            }

            void LoadDic(List <XmlDocument> dic, string webPath, string userPath, string defaultContent)
            {
                if (!File.Exists(webPath))
                {
                    File.WriteAllText(webPath, defaultContent, Encoding.Unicode);
                }
                dic.Clear();
                dic.Add(LoadXml(webPath));
                dic.Add(LoadXml(userPath));
            }

            LoadDic(UwpModeItemsDic, AppConfig.WebUwpModeItemsDic,
                    AppConfig.UserUwpModeItemsDic, Properties.Resources.UwpModeItemsDic);
            LoadDic(EnhanceMenusDic, AppConfig.WebEnhanceMenusDic,
                    AppConfig.UserEnhanceMenusDic, Properties.Resources.EnhanceMenusDic);
            LoadDic(DetailedEditDic, AppConfig.WebDetailedEditDic,
                    AppConfig.UserDetailedEditDic, Properties.Resources.DetailedEditDic);

            EnhanceMenuPathDic.Clear();
            for (int i = 0; i < 2; i++)
            {
                XmlDocument doc = EnhanceMenusDic[i];
                if (doc?.DocumentElement == null)
                {
                    continue;
                }
                foreach (XmlNode pathXN in doc.SelectNodes("Data/Group/RegPath"))
                {
                    if (EnhanceMenuPathDic.ContainsKey(pathXN.InnerText))
                    {
                        continue;
                    }
                    EnhanceMenuPathDic.Add(pathXN.InnerText, i == 1);
                }
            }

            DetailedEditGuidDic.Clear();
            for (int i = 0; i < 2; i++)
            {
                XmlDocument doc = DetailedEditDic[i];
                if (doc?.DocumentElement == null)
                {
                    continue;
                }
                foreach (XmlNode guidXN in doc.SelectNodes("Data/Group/Guid"))
                {
                    if (GuidEx.TryParse(guidXN.InnerText, out Guid guid))
                    {
                        if (DetailedEditGuidDic.ContainsKey(guid))
                        {
                            continue;
                        }
                        DetailedEditGuidDic.Add(guid, i == 1);
                    }
                }
            }
        }
示例#17
0
 public static Encoding GetFileCharset(string filePath)
 {
     return(EncodingType.GetType(filePath));
 }
示例#18
0
        protected override RESULT Process(StringBuilder messager)
        {
            var dir = Config.Instance.INFO.ImportSetting.DirInfo;

            if (dir == null || !Directory.Exists(dir.FullName))
            {
                return(RESULT.OK);
            }
            var files = Directory.GetFiles(dir.FullName).Where(f => f.Trim().ToLower().EndsWith(".txt"));

            if (files == null || files.Count() <= 0)
            {
                return(RESULT.OK);
            }

            //Files Loading...
            var del = true; var count = 0; var total = 0;
            var file = new FileInfo(files.First());

            logger.Write(TYPE.INFO, string.Format("1.importing file({0})...", file.Name));
            try
            {
                using (var templates = Config.Instance.INFO.ImportSetting.Templates)
                {
                    Template <TemplateUnit> template = null;
                    using (var reader = new StreamReader(File.OpenRead(file.FullName), EncodingType.GetType(file.FullName)))
                    {
                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();
                            if ((template = templates.MatchedTemplate) == null)
                            {
                                templates.Match(line);
                            }
                            else
                            {
                                if (template.Table == TABLES.NONE)
                                {
                                    logger.Write(TYPE.WARNING, string.Format("template({0}) is invalid.", template.Name));
                                    break;
                                }

                                switch (template.Table)
                                {
                                case TABLES.STK_GENERAL_M:
                                    if (SaveEntity(ExportEntity <DBTStkGeneralEntity>(line, template)))
                                    {
                                        count++;
                                    }
                                    total++;
                                    break;

                                case TABLES.STK_DAILY_TD:
                                    var code1 = DBTStkDailyEntity.FetchCode(file.Name);
                                    if (count <= 0)
                                    {
                                        if (!ClearDaily(code1))
                                        {
                                            continue;
                                        }
                                    }
                                    if (SaveEntity(ExportEntity <DBTStkDailyEntity>(line, template), code1))
                                    {
                                        count++;
                                    }
                                    total++;
                                    break;

                                case TABLES.STK_MINUTE_TD:
                                    var code2 = DBTStkMinuteEntity.FetchCode(file.Name);
                                    if (count <= 0)
                                    {
                                        if (!ClearMinute(code2))
                                        {
                                            continue;
                                        }
                                    }
                                    if (SaveEntity(ExportEntity <DBTStkMinuteEntity>(line, template), code2))
                                    {
                                        count++;
                                    }
                                    total++;
                                    break;

                                case TABLES.IDX_GENERAL_M:
                                    if (SaveEntity(ExportEntity <DBTIdxGeneralEntity>(line, template)))
                                    {
                                        count++;
                                    }
                                    total++;
                                    break;

                                case TABLES.STK_FAVORITE_M:
                                    if (SaveEntity(ExportEntity <DBTStkFavoriteEntity>(line, template)))
                                    {
                                        count++;
                                    }
                                    total++;
                                    break;
                                }
                            }
                        }
                    }

                    if (template != null)
                    {
                        switch (template.Table)
                        {
                        case TABLES.STK_DAILY_TD:
                            if (count > 0)
                            {
                                CalculateDaily(DBTStkDailyEntity.FetchCode(file.Name));
                            }
                            break;
                        }
                    }
                }
            }
            catch (IOException err)
            {
                logger.Write(TYPE.ERROR, string.Format("import file({0}) failed(IOException:{1}).", file.Name, err.Message));
                del = false;
            }
            catch (UnauthorizedAccessException err)
            {
                logger.Write(TYPE.ERROR, string.Format("import file({0}) failed(UnauthorizedAccessException:{1}).", file.Name, err.Message));
                del = false;
            }
            catch (Exception err)
            {
                logger.Write(err);
            }
            finally
            {
                logger.Write(TYPE.INFO, string.Format("2.imported data rows({0}/{1})", count, total));
                if (del)
                {
                    File.Delete(file.FullName);
                }
            }

            return(RESULT.OK);
        }
示例#19
0
        private async Task <int> Work(string filePath, string cookiePath)
        {
            string cookie = File.ReadAllText(cookiePath, EncodingType.GetType(cookiePath));

            var fileEncoding  = EncodingType.GetType(filePath);
            var fileContent   = File.ReadAllText(filePath, fileEncoding);
            var fileInfo      = new FileInfo(filePath);
            var fileExtension = fileInfo.Extension;
            var fileDir       = fileInfo.DirectoryName;

            var imgProc = new ImageProcessor();
            var imgList = imgProc.Process(fileContent);

            Console.WriteLine($"提取图片成功,共{imgList.Count}个.");

            var uploader = new ClientUploader("https://www.imooc.com");

            var replaceDic = new Dictionary <string, string>();

            foreach (var img in imgList)
            {
                string imgPhyPath = Path.Combine(fileDir, img);

                Console.WriteLine($"正在上传图片:{imgPhyPath}");
                try
                {
                    var res = await uploader.UploadAsync(imgPhyPath, "/article/ajaxuploadimg", "photo",
                                                         new Dictionary <string, string>()
                    {
                        ["Cookie"] = cookie
                    });

                    //校验
                    var json = JObject.Parse(res);
                    if (json.Value <int>("result") != 0)
                    {
                        Console.WriteLine("Cookie无效!");
                        return(1);
                    }

                    var httpImgPath = json["data"].Value <string>("imgpath");

                    replaceDic.Add(img, httpImgPath);

                    Console.WriteLine("上传成功!");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"处理失败!{e.Message}");
                    return(1);
                }
            }

            var    newContent  = imgProc.Replace(replaceDic, fileContent);
            string newFileName = filePath.Substring(0, filePath.LastIndexOf('.')) + "-imooc" + fileExtension;

            File.WriteAllText(newFileName, newContent, fileEncoding);

            Console.WriteLine($"处理完成!文件保存在:{newFileName}");

            return(0);
        }
示例#20
0
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Directory.Exists(textBox2.Text))
                {
                    MessageBox.Show("所选目录不存在!");
                    return;
                }
                DirectoryInfo root  = new DirectoryInfo(textBox2.Text);
                FileInfo[]    files = root.GetFiles("*.asp", SearchOption.AllDirectories);
                for (int i = 0; i < files.Count(); i++)
                {
                    if (files[i].Extension == ".asp")
                    {
                        if (files[i].DirectoryName.IndexOf("_vti_cnf") > -1 || files[i].DirectoryName.IndexOf("trans") > -1)
                        {
                            continue;
                        }
                        var haschange = false;

                        var str = File.ReadAllText(files[i].FullName, EncodingType.GetType(files[i].FullName));
                        if (str.ToLower().IndexOf(textBox3.Text.ToLower()) == -1)
                        {
                            continue;
                        }
                        if (str.IndexOf("Response.CodePage") == -1)
                        {
                            var reg = new Regex("%>");
                            str       = reg.Replace(str, " CODEPAGE=\"65001\"%>\r\n<% Response.CodePage=65001%>\r\n<% Response.Charset=\"UTF-8\" %>", 1);
                            haschange = true;
                        }
                        if (str.IndexOf("../../../../global.asa") == -1)
                        {
                            str       = str.Replace("../../global.asa", "../../../../global.asa");
                            haschange = true;
                        }
                        if (str.IndexOf("../../../../_ScriptLibrary") == -1)
                        {
                            str       = str.Replace("../../_ScriptLibrary", "../../../../_ScriptLibrary");
                            haschange = true;
                        }
                        var strlist    = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                        var strlist_en = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                        var strlist_es = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                        var strlist_vn = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                        for (int k = 0; k < strlist.Length; k++)
                        {
                            if (strlist[k].ToLower().IndexOf("\" values") > -1 || strlist[k].ToLower().IndexOf("update ") > -1 || strlist[k].ToLower().IndexOf("delete ") > -1 || strlist[k].ToLower().IndexOf("insert ") > -1)
                            {
                                continue;
                            }
                            var chs = Common.GetChinese(strlist[k].Replace("http://", "").Replace("https://", "").Replace("\t", " ")
                                                        .Split(new string[] { "<!-" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "//" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "*" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "/*" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "<option" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "<OPTION" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { " from " }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { " FROM" }, StringSplitOptions.None)[0],
                                                        files[i].FullName + " 行号:" + (k + 1));
                            if (chs.Count > 0)
                            {
                                chs       = chs.OrderByDescending(q => q.name.Length).ToList();
                                haschange = true;
                                for (int j = 0; j < chs.Count; j++)
                                {
                                    var dt = DBHelper.GetMany(string.Format("select {0},{1},{2} from a_trans where name_cn='{3}'", "name_en", "name_es", "name_vn", chs[j].name));
                                    if (dt.Rows.Count > 0)
                                    {
                                        strlist_en[k] = strlist_en[k].Replace(chs[j].name, dt.Rows[0]["name_en"].ToString());
                                        strlist_es[k] = strlist_es[k].Replace(chs[j].name, dt.Rows[0]["name_es"].ToString());
                                        strlist_vn[k] = strlist_vn[k].Replace(chs[j].name, dt.Rows[0]["name_vn"].ToString());
                                    }
                                }
                            }
                        }
                        if (haschange)
                        {
                            try
                            {
                                if (File.GetAttributes(files[i].FullName).ToString().IndexOf("ReadOnly") != -1)
                                {
                                    File.SetAttributes(files[i].FullName, FileAttributes.Normal);
                                }
                                var path_en = "/trans/EN";
                                var path_es = "/trans/ES";
                                var path_vn = "/trans/VN";
                                if (files[i].FullName.IndexOf("\\") > -1)
                                {
                                    path_en = "\\trans\\EN";
                                    path_es = "\\trans\\ES";
                                    path_vn = "\\trans\\VN";
                                }
                                var path = textBox2.Text;
                                if (textBox2.Text.LastIndexOf("/") == textBox2.Text.Length - 1 || textBox2.Text.LastIndexOf("\\") == textBox2.Text.Length - 1)
                                {
                                    path = textBox2.Text.Substring(0, textBox2.Text.Length - 1);
                                }
                                if (!Directory.Exists(Path.GetDirectoryName(files[i].FullName.Replace(path, path + path_en))))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(files[i].FullName.Replace(path, path + path_en)));
                                }
                                if (!Directory.Exists(Path.GetDirectoryName(files[i].FullName.Replace(path, path + path_es))))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(files[i].FullName.Replace(path, path + path_es)));
                                }
                                if (!Directory.Exists(Path.GetDirectoryName(files[i].FullName.Replace(path, path + path_vn))))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(files[i].FullName.Replace(path, path + path_vn)));
                                }
                                File.WriteAllText(files[i].FullName.Replace(path, path + path_en), string.Join("\r\n", strlist_en), Encoding.UTF8);
                                File.WriteAllText(files[i].FullName.Replace(path, path + path_es), string.Join("\r\n", strlist_es), Encoding.UTF8);
                                File.WriteAllText(files[i].FullName.Replace(path, path + path_vn), string.Join("\r\n", strlist_vn), Encoding.UTF8);
                            }
                            catch (Exception exe)
                            {
                                label1.Text += exe.Message + "\r\n";
                            }
                        }
                    }
                }

                MessageBox.Show("Succsee!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("fail" + ex.Message);
            }
        }
示例#21
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(textBox1.Text))
            {
                MessageBox.Show("所选目录不存在!");
                return;
            }
            dataGridView1.Rows.Clear();
            dataGridView1.Refresh();
            var ChineseWordPath = Path.Combine(Environment.CurrentDirectory, "ChineseWord.json");
            var strarr          = new List <MyObj>();
            var newstrarr       = new List <MyObj>();

            if (File.Exists(ChineseWordPath))
            {
                strarr = JsonConvert.DeserializeObject <List <MyObj> >(File.ReadAllText(ChineseWordPath, Encoding.UTF8));
            }

            DirectoryInfo root = new DirectoryInfo(textBox1.Text);

            FileInfo[] files = root.GetFiles("*.asp", checkBox1.Checked? SearchOption.AllDirectories:SearchOption.TopDirectoryOnly);
            for (int i = 0; i < files.Count(); i++)
            {
                if (files[i].Extension == ".asp")
                {
                    if (files[i].DirectoryName.IndexOf("_vti_cnf") > -1)
                    {
                        continue;
                    }

                    var str = File.ReadAllText(files[i].FullName, EncodingType.GetType(files[i].FullName));

                    // Regex reg = new Regex(@"(?<=\/\*)[.\s\S]*?(?=(\*\/))", RegexOptions.Multiline | RegexOptions.Singleline);

                    var strlist = str.Replace("  ", " ").Replace("  ", " ").Replace("  ", " ").Replace("  ", " ").Replace("  ", " ").Replace("  ", " ")
                                  .Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    for (int k = 0; k < strlist.Length; k++)
                    {
                        if (strlist[k].ToLower().IndexOf("update ") > -1 || strlist[k].ToLower().IndexOf("delete ") > -1 || strlist[k].ToLower().IndexOf("insert ") > -1 || strlist[k].ToLower().IndexOf("where ") > -1)
                        {
                            continue;
                        }

                        newstrarr.AddRange(Common.GetChinese(strlist[k].Replace("http://", "").Replace("https://", "")
                                                             .Split(new string[] { "<!-" }, StringSplitOptions.None)[0]
                                                             .Split(new string[] { "//" }, StringSplitOptions.None)[0]
                                                             .Split(new string[] { "*" }, StringSplitOptions.None)[0]
                                                             .Split(new string[] { "/*" }, StringSplitOptions.None)[0]
                                                             .Split(new string[] { "<option" }, StringSplitOptions.None)[0]
                                                             .Split(new string[] { "<OPTION" }, StringSplitOptions.None)[0]
                                                             .Split(new string[] { " from " }, StringSplitOptions.None)[0]
                                                             .Split(new string[] { " FROM" }, StringSplitOptions.None)[0],
                                                             files[i].FullName + " 行号:" + (k + 1)));
                    }
                }
            }
            var list = newstrarr.Distinct(new Compare()).ToList();

            for (int j = 0; j < list.Count(); j++)
            {
                if (strarr.FindAll(q => q.name == list[j].name).Count == 0)
                {
                    var index = dataGridView1.Rows.Add();
                    dataGridView1.Rows[index].Cells[0].Value = list[j].name.Trim();
                    dataGridView1.Rows[index].Cells[1].Value = string.Join(" | ", list[j].dir);
                }
            }
            strarr.AddRange(list);
            File.WriteAllText(ChineseWordPath, JsonConvert.SerializeObject(strarr.Distinct(new Compare()).ToList()), Encoding.UTF8);
        }
示例#22
0
        public void ExecuteExport(long id)
        {
            using (var ctx = new DbMonitorEntities())
            {
                var me  = ctx.MirrorExport.Find(id);
                var dic = ctx.Dictionary.Where(d => d.DTypeCode == "OracleExport" && d.DEnable == 1).ToList();
                var sc  = ctx.SessionConnection.Find(me.SCID);

                me.MEStatus    = "开始导出";
                me.EditingTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                ctx.SaveChanges();

                string dblink  = string.Format("dblink{0}", id),
                       user    = me.MEUser,
                       pwd     = me.MEPassword,
                       host    = sc.SCHostName,
                       service = sc.SCServiceName;
                long port      = sc.SCPort.Value;

                using (var dal = new OracleDAL(connStr))
                {
                    try
                    {
                        StringBuilder sbSql = new StringBuilder();
                        //存在就先删除
                        var cnt = Convert.ToInt32(dal.ExecuteScalar(string.Format("select count(1) from dba_db_links where db_link='{0}'", dblink.ToUpper())));
                        if (cnt > 0)
                        {
                            dal.ExecuteNonQuery(string.Format("drop public database link {0}", dblink.ToUpper()));
                        }

                        //再添加
                        sbSql.AppendFormat("create public database link {0} connect to {1} identified by {2} using",
                                           dblink, user, pwd);
                        sbSql.AppendFormat("'(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL = TCP)(HOST = {0})(PORT = {1})))(CONNECT_DATA =(SERVICE_NAME = {2})))'",
                                           host, port, service);

                        dal.ExecuteNonQuery(sbSql.ToString());
                    }
                    catch (Exception ex)
                    {
                        me.MEStatus    = "创建dblink失败";
                        me.EditingTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        ctx.SaveChanges();
                        LogHelper.WriteError(ex, string.Format("导出Oracle数据库时创建dblink失败,会话ID:{0}", id));
                        return;
                    }
                }
                me.MEStatus    = "创建dblink成功";
                me.EditingTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                ctx.SaveChanges();

                List <string> cmds = new List <string>();
                //变量设置是必须的
                string directory   = dic.Where(d => d.DCode == "directory").FirstOrDefault().DName,
                       oracle_base = dic.Where(d => d.DCode == "oracle_base").FirstOrDefault().DName,
                       oracle_home = dic.Where(d => d.DCode == "oracle_home").FirstOrDefault().DName,
                       oracle_sid  = dic.Where(d => d.DCode == "oracle_sid").FirstOrDefault().DName,
                       user_local  = dic.Where(d => d.DCode == "user").FirstOrDefault().DName,
                       pwd_local   = dic.Where(d => d.DCode == "pwd").FirstOrDefault().DName;

                cmds.Add(string.Format("set ORACLE_BASE={0}", oracle_base));
                cmds.Add(string.Format("set ORACLE_HOME=%ORACLE_BASE%{0}", oracle_home));
                cmds.Add(string.Format("set ORACLE_SID={0}", oracle_sid));
                cmds.Add(@"set PATH=%path%;%ORACLE_HOME%\bin");

                string file = me.MEFileName, log = me.MELogFile, schemas = me.MESchemas, timestamp = me.MEExportTime;
                //使用StringBuilder注意参数之间的空格
                StringBuilder sbExp = new StringBuilder();
                sbExp.AppendFormat("%ORACLE_HOME%\\bin\\expdp {0}/{1} directory={2} dumpfile={3} logfile={4} network_link={5} schemas={6} ",
                                   user_local, pwd_local, directory, file, log, dblink, schemas);
                sbExp.AppendFormat("flashback_time=\\\"to_timestamp('{0}','yyyy-mm-dd hh24:mi:ss')\\\"", timestamp);

                cmds.Add(sbExp.ToString());
                CmdHelper.Execute(cmds.ToArray());

                var backup_dir = dic.Where(d => d.DCode == "backup_dir").FirstOrDefault().DName;
                var logfile    = Path.Combine(backup_dir, log);

                if (File.Exists(logfile))
                {
                    string text = File.ReadAllText(logfile, EncodingType.GetType(logfile));
                    Console.WriteLine(text);

                    string pattern = @"作业[\s\S]+完成";

                    if (Regex.IsMatch(text, pattern))
                    {
                        me.MEStatus    = "导出成功";
                        me.EditingTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        ctx.SaveChanges();
                    }
                    else
                    {
                        me.MEStatus    = "导出失败";
                        me.EditingTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        ctx.SaveChanges();
                    }
                }
                else
                {
                    me.MEStatus    = "导出失败";
                    me.EditingTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    ctx.SaveChanges();
                }
            }
        }
示例#23
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Directory.Exists(textBox1.Text))
                {
                    MessageBox.Show("所选目录不存在!");
                    return;
                }
                var lang = "";
                if (radioButton1.Checked)
                {
                    lang = "name_en";
                }
                else if (radioButton2.Checked)
                {
                    lang = "name_es";
                }
                else if (radioButton3.Checked)
                {
                    lang = "name_vn";
                }
                DirectoryInfo root  = new DirectoryInfo(textBox1.Text);
                FileInfo[]    files = root.GetFiles("*.asp", checkBox1.Checked ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                for (int i = 0; i < files.Count(); i++)
                {
                    if (files[i].Extension == ".asp")
                    {
                        if (files[i].DirectoryName.IndexOf("_vti_cnf") > -1 || files[i].DirectoryName.IndexOf("trans") > -1)
                        {
                            continue;
                        }
                        var haschange = false;

                        var str = File.ReadAllText(files[i].FullName, EncodingType.GetType(files[i].FullName));

                        if (str.IndexOf("Response.CodePage") == -1)
                        {
                            var reg = new Regex("%>");
                            str       = reg.Replace(str, " CODEPAGE=\"65001\"%>\r\n<% Response.CodePage=65001%>\r\n<% Response.Charset=\"UTF-8\" %>", 1);
                            haschange = true;
                        }
                        if (str.IndexOf("../../../../global.asa") == -1)
                        {
                            str       = str.Replace("../../global.asa", "../../../../global.asa");
                            haschange = true;
                        }
                        if (str.IndexOf("../../../../_ScriptLibrary") == -1)
                        {
                            str       = str.Replace("../../_ScriptLibrary", "../../../../_ScriptLibrary");
                            haschange = true;
                        }
                        var strlist = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                        for (int k = 0; k < strlist.Length; k++)
                        {
                            if (strlist[k].ToLower().IndexOf("\" values") > -1 || strlist[k].ToLower().IndexOf("update ") > -1 || strlist[k].ToLower().IndexOf("delete ") > -1 || strlist[k].ToLower().IndexOf("insert ") > -1)
                            {
                                continue;
                            }
                            var chs = Common.GetChinese(strlist[k].Replace("http://", "").Replace("https://", "")
                                                        .Split(new string[] { "<!-" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "//" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "*" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "/*" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "<option" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { "<OPTION" }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { " from " }, StringSplitOptions.None)[0]
                                                        .Split(new string[] { " FROM" }, StringSplitOptions.None)[0],
                                                        files[i].FullName + " 行号:" + (k + 1));
                            if (chs.Count > 0)
                            {
                                haschange = true;
                                for (int j = 0; j < chs.Count; j++)
                                {
                                    var getlang = DBHelper.GetSingle(string.Format("select {0} from a_trans where name_cn='{1}'", lang, chs[j].name));
                                    if (getlang != null && getlang.ToString() != "")
                                    {
                                        strlist[k] = strlist[k].Replace(chs[j].name, getlang.ToString());
                                    }
                                }
                            }
                        }
                        if (haschange)
                        {
                            try
                            {
                                if (File.GetAttributes(files[i].FullName).ToString().IndexOf("ReadOnly") != -1)
                                {
                                    File.SetAttributes(files[i].FullName, FileAttributes.Normal);
                                }
                                File.WriteAllText(files[i].FullName, string.Join("\r\n", strlist), Encoding.UTF8);
                            }
                            catch (Exception exe)
                            {
                                label1.Text += exe.Message + "\r\n";
                            }
                        }
                    }
                }

                MessageBox.Show("Succsee!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("fail" + ex.Message);
            }
        }
示例#24
0
        private void LoadDocItems(string xmlPath, GroupPathItem groupItem)
        {
            if (!File.Exists(xmlPath))
            {
                return;
            }
            this.AddItem(groupItem);
            XmlDocument doc = new XmlDocument();

            try { doc.LoadXml(File.ReadAllText(xmlPath, EncodingType.GetType(xmlPath)).Trim()); }
            catch (Exception e) { MessageBoxEx.Show(e.Message); return; }
            foreach (XmlElement groupXE in doc.DocumentElement.ChildNodes)
            {
                try
                {
                    Guid guid = Guid.Empty;
                    if (groupXE.HasAttribute("Guid"))
                    {
                        if (GuidEx.TryParse(groupXE.GetAttribute("Guid"), out guid))
                        {
                            if (!File.Exists(GuidInfo.GetFilePath(guid)))
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    SubGroupItem        subGroupItem;
                    bool                isIniGroup = groupXE.HasAttribute("IsIniGroup");
                    string              attribute  = isIniGroup ? "FilePath" : "RegPath";
                    ObjectPath.PathType pathType   = isIniGroup ? ObjectPath.PathType.File : ObjectPath.PathType.Registry;
                    subGroupItem = new SubGroupItem(groupXE.GetAttribute(attribute), pathType)
                    {
                        Text  = groupXE.GetAttribute("Text"),
                        Image = GuidInfo.GetImage(guid)
                    };
                    if (subGroupItem.Text.IsNullOrWhiteSpace())
                    {
                        subGroupItem.Text = GuidInfo.GetText(guid);
                    }
                    this.AddItem(subGroupItem);

                    string GetRuleFullRegPath(string regPath)
                    {
                        if (string.IsNullOrEmpty(regPath))
                        {
                            regPath = subGroupItem.TargetPath;
                        }
                        else if (regPath.StartsWith("\\"))
                        {
                            regPath = subGroupItem.TargetPath + regPath;
                        }
                        return(regPath);
                    };

                    foreach (XmlElement itemXE in groupXE.ChildNodes)
                    {
                        try
                        {
                            if (!EnhanceMenusList.JudgeOSVersion(itemXE))
                            {
                                continue;
                            }
                            RuleItem ruleItem;
                            ItemInfo info = new ItemInfo
                            {
                                Text            = itemXE.GetAttribute("Text"),
                                Tip             = itemXE.GetAttribute("Tip"),
                                RestartExplorer = itemXE.HasAttribute("RestartExplorer"),
                            };
                            int defaultValue = 0, maxValue = 0, minValue = 0;
                            if (itemXE.HasAttribute("IsNumberItem"))
                            {
                                XmlElement ruleXE = (XmlElement)itemXE.SelectSingleNode("Rule");
                                defaultValue = ruleXE.HasAttribute("Default") ? Convert.ToInt32(ruleXE.GetAttribute("Default")) : 0;
                                maxValue     = ruleXE.HasAttribute("Max") ? Convert.ToInt32(ruleXE.GetAttribute("Max")) : int.MaxValue;
                                minValue     = ruleXE.HasAttribute("Min") ? Convert.ToInt32(ruleXE.GetAttribute("Min")) : int.MinValue;
                            }

                            if (isIniGroup)
                            {
                                XmlElement ruleXE  = (XmlElement)itemXE.SelectSingleNode("Rule");
                                string     iniPath = ruleXE.GetAttribute("FilePath");
                                if (iniPath.IsNullOrWhiteSpace())
                                {
                                    iniPath = subGroupItem.TargetPath;
                                }
                                string section = ruleXE.GetAttribute("Section");
                                string keyName = ruleXE.GetAttribute("KeyName");
                                if (itemXE.HasAttribute("IsNumberItem"))
                                {
                                    var rule = new NumberIniRuleItem.IniRule
                                    {
                                        IniPath      = iniPath,
                                        Section      = section,
                                        KeyName      = keyName,
                                        DefaultValue = defaultValue,
                                        MaxValue     = maxValue,
                                        MinValue     = maxValue
                                    };
                                    ruleItem = new NumberIniRuleItem(rule, info);
                                }
                                else if (itemXE.HasAttribute("IsStringItem"))
                                {
                                    var rule = new StringIniRuleItem.IniRule
                                    {
                                        IniPath  = iniPath,
                                        Secation = section,
                                        KeyName  = keyName
                                    };
                                    ruleItem = new StringIniRuleItem(rule, info);
                                }
                                else
                                {
                                    var rule = new VisbleIniRuleItem.IniRule
                                    {
                                        IniPath      = iniPath,
                                        Section      = section,
                                        KeyName      = keyName,
                                        TurnOnValue  = ruleXE.HasAttribute("On") ? ruleXE.GetAttribute("On") : null,
                                        TurnOffValue = ruleXE.HasAttribute("Off") ? ruleXE.GetAttribute("Off") : null,
                                    };
                                    ruleItem = new VisbleIniRuleItem(rule, info);
                                }
                            }
                            else
                            {
                                if (itemXE.HasAttribute("IsNumberItem"))
                                {
                                    XmlElement ruleXE = (XmlElement)itemXE.SelectSingleNode("Rule");
                                    var        rule   = new NumberRegRuleItem.RegRule
                                    {
                                        RegPath      = GetRuleFullRegPath(ruleXE.GetAttribute("RegPath")),
                                        ValueName    = ruleXE.GetAttribute("ValueName"),
                                        ValueKind    = GetValueKind(ruleXE.GetAttribute("ValueKind")),
                                        DefaultValue = defaultValue,
                                        MaxValue     = maxValue,
                                        MinValue     = minValue
                                    };
                                    ruleItem = new NumberRegRuleItem(rule, info);
                                }
                                else if (itemXE.HasAttribute("IsStringItem"))
                                {
                                    XmlElement ruleXE = (XmlElement)itemXE.SelectSingleNode("Rule");
                                    var        rule   = new StringRegRuleItem.RegRule
                                    {
                                        RegPath   = GetRuleFullRegPath(ruleXE.GetAttribute("RegPath")),
                                        ValueName = ruleXE.GetAttribute("ValueName"),
                                    };
                                    ruleItem = new StringRegRuleItem(rule, info);
                                }
                                else
                                {
                                    XmlNodeList ruleXNList = itemXE.SelectNodes("Rule");
                                    var         rules      = new VisibleRegRuleItem.RegRule[ruleXNList.Count];
                                    for (int i = 0; i < ruleXNList.Count; i++)
                                    {
                                        XmlElement ruleXE = (XmlElement)ruleXNList[i];
                                        rules[i] = new VisibleRegRuleItem.RegRule
                                        {
                                            RegPath   = GetRuleFullRegPath(ruleXE.GetAttribute("RegPath")),
                                            ValueName = ruleXE.GetAttribute("ValueName"),
                                            ValueKind = GetValueKind(ruleXE.GetAttribute("ValueKind"))
                                        };
                                        string turnOn  = ruleXE.HasAttribute("On") ? ruleXE.GetAttribute("On") : null;
                                        string turnOff = ruleXE.HasAttribute("Off") ? ruleXE.GetAttribute("Off") : null;
                                        switch (rules[i].ValueKind)
                                        {
                                        case RegistryValueKind.Binary:
                                            rules[i].TurnOnValue = turnOn != null?EnhanceMenusList.ConvertToBinary(turnOn) : null;

                                            rules[i].TurnOffValue = turnOff != null?EnhanceMenusList.ConvertToBinary(turnOff) : null;

                                            break;

                                        case RegistryValueKind.DWord:
                                            if (turnOn == null)
                                            {
                                                rules[i].TurnOnValue = null;
                                            }
                                            else
                                            {
                                                rules[i].TurnOnValue = Convert.ToInt32(turnOn);
                                            }
                                            if (turnOff == null)
                                            {
                                                rules[i].TurnOffValue = null;
                                            }
                                            else
                                            {
                                                rules[i].TurnOffValue = Convert.ToInt32(turnOff);
                                            }
                                            break;

                                        default:
                                            rules[i].TurnOnValue  = turnOn;
                                            rules[i].TurnOffValue = turnOff;
                                            break;
                                        }
                                    }
                                    ruleItem = new VisibleRegRuleItem(rules, info);
                                }
                            }
                            this.AddItem(ruleItem);
                            ruleItem.FoldGroupItem = subGroupItem;
                        }
                        catch { continue; }
                    }
                    subGroupItem.HideWhenNoSubItem();
                    subGroupItem.FoldGroupItem = groupItem;
                }
                catch { continue; }
            }
            groupItem.IsFold = true;
            groupItem.HideWhenNoSubItem();
        }
示例#25
0
        public static ECharset GetFileCharset(string filePath)
        {
            Encoding encoding = EncodingType.GetType(filePath);

            return(ECharsetUtils.GetEnumType(encoding.BodyName));
        }
示例#26
0
        private async Task <int> Work(string filePath, string cookiePath)
        {
            string cookie = File.ReadAllText(cookiePath, EncodingType.GetType(cookiePath));

            var fileEncoding  = EncodingType.GetType(filePath);
            var fileContent   = File.ReadAllText(filePath, fileEncoding);
            var fileInfo      = new FileInfo(filePath);
            var fileExtension = fileInfo.Extension;
            var fileDir       = fileInfo.DirectoryName;

            var imgProc = new ImageProcessor();
            var imgList = imgProc.Process(fileContent);

            Console.WriteLine($"提取图片成功,共{imgList.Count}个.");

            var uploader = new ClientUploader("https://cloud.tencent.com");

            var replaceDic = new Dictionary <string, string>();

            foreach (var img in imgList)
            {
                string imgPhyPath = Path.Combine(fileDir, img);

                Console.WriteLine($"正在上传图片:{imgPhyPath}");
                try
                {
                    var res = await uploader.UploadAsync(imgPhyPath, $"/developer/services/ajax/image?action=UploadImage&uin={Uin}&csrfCode={Csrf}", "image",
                                                         new Dictionary <string, string>()
                    {
                        ["Cookie"] = cookie
                    });

                    //校验
                    var json = JObject.Parse(res);
                    if (json.Value <int>("code") != 0)
                    {
                        Console.WriteLine("Cookie或uin、csrf code 无效!");
                        return(1);
                    }

                    var httpImgPath = json["data"].Value <string>("url");

                    replaceDic.Add(img, httpImgPath);

                    Console.WriteLine("上传成功!");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"处理失败!{e.Message}");
                    return(1);
                }
            }

            var    newContent  = imgProc.Replace(replaceDic, fileContent);
            string newFileName = filePath.Substring(0, filePath.LastIndexOf('.')) + "-tcloud" + fileExtension;

            File.WriteAllText(newFileName, newContent, fileEncoding);

            Console.WriteLine($"处理完成!文件保存在:{newFileName}");

            return(0);
        }