当前位置: 首页>>代码示例>>C#>>正文


C# Regex.Trim方法代码示例

本文整理汇总了C#中System.Text.RegularExpressions.Regex.Trim方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.Trim方法的具体用法?C# Regex.Trim怎么用?C# Regex.Trim使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Text.RegularExpressions.Regex的用法示例。


在下文中一共展示了Regex.Trim方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ParseAdditionalInformation

 protected override void ParseAdditionalInformation()
 {
     string bankName = new Regex(@"/BBK/.*\|?").Match(statementLine).Value;
     if (!string.IsNullOrEmpty(bankName))
     {
         bankName = bankName.Substring(5);
         if (bankName.EndsWith("|"))
         {
             bankName = bankName.Substring(0, bankName.Length - 1);
         }
         int vertical = bankName.IndexOf("|");
         if (-1 < vertical)
         {
             bankName = bankName.Substring(0, vertical);
         }
         bankStatement.CptyBankName = bankName.Trim();
     }
     AddInformation();
     //put tag 86 information to remark
     string[] remarks = statementLine.Split(new string[] { TAG_ADDITIONAL_INFO }, StringSplitOptions.None);
     if (remarks.Length > 1)
     {
         bankStatement.Remark = remarks[1];
     }
 }
开发者ID:keenkid,项目名称:BankReportService,代码行数:25,代码来源:HSBCMT940.cs

示例2: CleanUp

 /// <summary>
 /// Удаляет комментарии
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 private string CleanUp(string input)
 {
     var copy = input;
     copy = new Regex("(/\\*(.|[\r\n])*?\\*/)|(//.*)")
                 .Replace(copy, "")
                 .Replace("\r", "")
                 .Replace("\n", "");
     return copy.Trim().ToLower();
 }
开发者ID:sbezludny,项目名称:CssOptimizer,代码行数:14,代码来源:CssStylesheet.cs

示例3: get

        public string get(string video_id, string owner_id, string token, string AccountID, string GroupID)
        {
            string tmp = new PostAPI().post("https://api.vk.com/method/video.add", ("owner_id=" + owner_id + "&video_id=" + video_id + "&access_token=" + token), null, null, AccountID, GroupID);
            string s = new Regex("{\"response\":([0-9]+)}").Match(tmp).Groups[1].Value;

            //Возврат результатов и очистка ресурсов
            AccountID = null; GroupID = null; video_id = null; owner_id = null; token = null; tmp = null;
            return (s != null && s.Trim() != "" ? s : s = null);
        }
开发者ID:korner-brazers,项目名称:VKNext,代码行数:9,代码来源:VideoADD.cs

示例4: get

        public static string get(string method, string argument, bool ResponseList = false)
        {
            string tmp = Browser.post("https://api.vk.com/method/" + method.Trim(), argument.Replace(" ", "").Trim()).Trim();
            string response = new Regex("^{\"response\":\\[(.+)\\]}$").Match(tmp).Groups[1].Value;

            //На случай ошибки, мы вернем данные об ошибке вместо нужных параметров
            if (response.Trim() != "")
                return (ResponseList ? tmp : response);
            else
                return tmp;
        }
开发者ID:korner-brazers,项目名称:VK-HashTag,代码行数:11,代码来源:result.cs

示例5: ToText

 public string ToText()
 {
     if (string.IsNullOrEmpty(text))
     {
         return string.Empty;
     }
     else
     {
         string txt = new Regex(@"\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?").Replace(text, "");
         return txt.Trim().Replace("\n", "<br>");
     }
 }
开发者ID:a01benson,项目名称:CouseManagement,代码行数:12,代码来源:RTF.cs

示例6: get

        public string get(string token)
        {
            int CountRefresh = 0;
            Refresh: string tmp = new PostAPI().post("https://api.vk.com/method/users.get", ("&access_token=" + token), null, null, null, null).Replace("\\/", "/").Replace(" ", "").ToLower().Trim();
            string id = new Regex("\"uid\":([0-9]+),?\"").Match(tmp).Groups[1].Value;

            //Проверка на капчу и получение URL
            if ((new Regex("userauthorizationfailed:invalidaccess_token").Match(tmp)).Success || CountRefresh == 3)
            {
                Console.WriteLine("Error UserGet.cs: {0}\nToken: {1}\nНажмите любую клавишу для завершения программы.", new Regex("\"error_msg\":\"([^\"]+)\"").Match(tmp).Groups[1].Value, token);
                Console.ReadKey();
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            else if ((id == null || id.Trim() == "") && CountRefresh != 3)
            {
                id = null; tmp = null; CountRefresh++; goto Refresh;
            }

            //Чистим ресурсы
            tmp = null; token = null;
            return id.Trim();
        }
开发者ID:korner-brazers,项目名称:VKNext,代码行数:22,代码来源:UserGet.cs

示例7: GetTextBetween

        public static string GetTextBetween(this string source, string endText, params string[] startText)
        {
            int startIndex = GetIndexAfter(source, startText);
            if (startIndex < 0) return null;

            int endIndex = source.IndexOf(endText, startIndex);
            if (endIndex < 0) throw new Exception(endText + " not found in string: " + source);

            string text = source.Substring(startIndex, endIndex - startIndex);

            // trim
            text = new Regex("&nbsp;").Replace(text, " ");
            text = text.Trim();

            return text;
        }
开发者ID:HackerChick,项目名称:ContentGrab,代码行数:16,代码来源:StringExtensions.cs

示例8: get

        public string get(string token, string gPost)
        {
            int CountRefresh = 0;
            Refresh: string tmp = new PostAPI().post("https://api.vkontakte.ru/method/photos.getWallUploadServer", ("group_id=" + gPost.Replace("-", "").Trim() + "&access_token=" + token), null, null, null, null).Replace("\\/", "/").Trim();
            string url = new Regex("\"upload_url\":\"([^\"]+)\"").Match(tmp).Groups[1].Value;

            //Проверка на капчу и получение URL
            if ((new Regex("userauthorizationfailed:invalidaccess_token").Match(tmp.ToLower().Replace(" ", ""))).Success || CountRefresh == 3)
            {
                Console.WriteLine("Error UploadURL.cs: {0}\nToken: {1}\nНажмите любую клавишу для завершения программы.", new Regex("\"error_msg\":\"([^\"]+)\"").Match(tmp).Groups[1].Value, token);
                Console.ReadKey();
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            else if ((url == null || url.Trim() == "") && CountRefresh != 3)
            {
                url = null; tmp = null; CountRefresh++; goto Refresh;
            }

            //Чистим ресурсы
            tmp = null; token = null; gPost = null;
            return url;
        }
开发者ID:korner-brazers,项目名称:VKNext,代码行数:22,代码来源:UploadURL.cs

示例9: CreateReader

        public static IReader CreateReader(string email, string password, string source)
        {
            LogWriter.CreateLogfile();
            Settings.Default.authToken = "";
            const string authUrl = GOOGLE_LOGIN_ADDRESS;

            var reader = new Reader(source);

            string response = HttpClient.SendPostRequest(authUrl, new
            {

                service = "reader",
                Email = email,
                Passwd = password,
                source="DesktopGoogleReader",
                accountType = "GOOGLE"
            }, false);

            LogWriter.WriteTextToLogFile("Response from Google");
            LogWriter.WriteTextToLogFile(response);

            string authToken = "";

            try
            {
                LogWriter.WriteTextToLogFile("Trying to get Auth Token");
                authToken = new Regex(@"Auth=(?<authToken>\S+)").Match(response).Result("${authToken}");
                LogWriter.WriteTextToLogFile("AuthToken is " + authToken);
                Settings.Default.authToken = authToken.Trim();
            }
            catch (Exception e)
            {
                LogWriter.WriteTextToLogFile(e);
                throw new ArgumentException("AuthToken parsing error: " + e.Message);
            }

            return reader;
        }
开发者ID:jasonwurzel,项目名称:GoogleReaderPodcastSync,代码行数:38,代码来源:Reader.cs

示例10: UploadCAPCHA

        private string UploadCAPCHA(string url)
        {
            try
            {
                //Типа разделитель и данные для работы
                string str = DateTime.Now.Ticks.ToString("x");
                byte[] boundary = Encoding.UTF8.GetBytes("\n--" + str + "\n");
                HttpWebRequest request = null;
                Stream stream = null, StreamHTML = null;
                StreamReader Reader = null;
                WebClient wc = new WebClient();
                WebResponse response = null;
                string result = null;

                try
                {
                    //Создаем подключение с URL для загрузки картинок
                    request = (HttpWebRequest)WebRequest.Create("http://antigate.com/in.php");
                    request.ContentType = "multipart/form-data; boundary=" + str;
                    request.Method = "POST";
                    request.KeepAlive = true;
                    request.MaximumAutomaticRedirections = 3;
                    request.ReadWriteTimeout = 1000 * 30;
                    request.Timeout = 1000 * 30;

                    //Хедеры
                    byte[] image = wc.DownloadData(url);
                    byte[] header = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"method\"\n\npost\n--{0}\n", str) +
                                                           string.Format("Content-Disposition: form-data; name=\"key\"\n\n{0}\n--{1}\n", conf.KeyAntigate, str) +
                                                           "Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\nContent-Type: \"image/jpg\"\n\n");

                    //Записываем в поток все данные
                    stream = request.GetRequestStream();
                    stream.Write(boundary, 0, boundary.Length);
                    stream.Write(header, 0, header.Length);
                    stream.Write(image, 0, image.Length);
                    stream.Write(boundary, 0, boundary.Length);
                    image = null; header = null;

                    //Возвращаем данные
                    response = request.GetResponse();
                    StreamHTML = response.GetResponseStream();
                    Reader = new StreamReader(StreamHTML);
                    result = new Regex(@"ok\|([0-9]+)").Match(Reader.ReadToEnd().ToLower()).Groups[1].Value;
                }
                catch { }
                finally
                {
                    //Чистим ресурсы
                    url = null; wc.Dispose(); wc = null; str = null; boundary = null;
                    if (Reader != null)
                    {
                        Reader.Close(); Reader.Dispose(); Reader = null;
                    }
                    if (StreamHTML != null)
                    {
                        StreamHTML.Close(); StreamHTML.Dispose(); StreamHTML = null;
                    }
                    if (response != null)
                    {
                        response.Close(); response.Dispose(); response = null;
                    }
                    if (stream != null)
                    {
                        stream.Close(); stream.Dispose(); stream = null;
                    }
                    if (request != null)
                    {
                        request.Abort(); request = null;
                    }
                }

                //Возвращаем результат
                return result != null ? (result.Trim() == "" ? null : result.Trim()) : null;
            }
            catch
            {
                return (url = null);
            }
        }
开发者ID:korner-brazers,项目名称:VKNext,代码行数:80,代码来源:Antigate.cs

示例11: MakeFileName

    /// <summary>
    /// Create the filename for the recording 
    /// </summary>
    /// <param name="recordingPath"></param>
    public void MakeFileName(string recordingPath)
    {
      TvBusinessLayer layer = new TvBusinessLayer();

      Setting setting;
      if (!IsSerie)
      {
        Log.Debug("Scheduler: MakeFileName() using \"moviesformat\" (_isSerie={0})", _isSerie);
        setting = layer.GetSetting("moviesformat", "%title%");
      }
      else
      {
        Log.Debug("Scheduler: MakeFileName() using \"seriesformat\" (_isSerie={0})", _isSerie);
        setting = layer.GetSetting("seriesformat", "%title%");
      }

      string strInput = "title%";
      if (setting != null)
      {
        if (setting.Value != null)
        {
          strInput = setting.Value;
        }
      }
      string subDirectory = string.Empty;
      string fullPath = recordingPath;
      string fileName;
      const string recEngineExt = ".ts";

      string[] TagNames = {
                            "%channel%",
                            "%title%",
                            "%name%",
                            "%series%",
                            "%episode%",
                            "%part%",
                            "%date%",
                            "%start%",
                            "%end%",
                            "%genre%",
                            "%startday%",
                            "%startmonth%",
                            "%startyear%",
                            "%starthh%",
                            "%startmm%",
                            "%endday%",
                            "%endmonth%",
                            "%endyear%",
                            "%endhh%",
                            "%endmm%"
                          };
      string[] TagValues = {
                             _schedule.ReferencedChannel().DisplayName.Trim(),
                             Program.Title.Trim(),
                             Program.EpisodeName.Trim(),
                             Program.SeriesNum.Trim(),
                             Program.EpisodeNum.Trim(),
                             Program.EpisodePart.Trim(),
                             Program.StartTime.ToString("yyyy-MM-dd"),
                             Program.StartTime.ToShortTimeString(),
                             Program.EndTime.ToShortTimeString(),
                             Program.Genre.Trim(),
                             Program.StartTime.ToString("dd"),
                             Program.StartTime.ToString("MM"),
                             Program.StartTime.ToString("yyyy"),
                             Program.StartTime.ToString("HH"),
                             Program.StartTime.ToString("mm"),
                             Program.EndTime.ToString("dd"),
                             Program.EndTime.ToString("MM"),
                             Program.EndTime.ToString("yyyy"),
                             Program.EndTime.ToString("HH"),
                             Program.EndTime.ToString("mm")
                           };

      for (int i = 0; i < TagNames.Length; i++)
      {
        strInput = Utils.ReplaceTag(strInput, TagNames[i], Utils.MakeFileName(TagValues[i]), "unknown");
        if (!strInput.Contains("%"))
        {
          break;
        }
      }

      int index = strInput.LastIndexOf('\\');
      if (index != -1)
      {
        subDirectory = strInput.Substring(0, index).Trim();
        fileName = strInput.Substring(index + 1).Trim();
      }
      else
        fileName = strInput.Trim();


      if (subDirectory != string.Empty)
      {
        subDirectory = Utils.RemoveTrailingSlash(subDirectory);
//.........这里部分代码省略.........
开发者ID:arangas,项目名称:MediaPortal-1,代码行数:101,代码来源:RecordingDetail.cs

示例12: LoadConf

        public LoadConf()
        {
            //Загрузка ключей и другого мусора
            if(File.Exists(conf.DirConf))
            {
                string s = File.ReadAllText(conf.DirConf).Replace(" ", "");
                conf.KeyAntigate = new Regex("KeyAntigate:([^;]+);").Match(s).Groups[1].Value;
                s = null;
            }

            //Загрузка данных по аккаунтам и группам
            foreach (string AccountDir in Directory.GetFiles(conf.DirAccount))
            {
                string account = Regex.Replace(Regex.Replace(File.ReadAllText(AccountDir), @"/\*[^\*]+\*/", ""), "//[^\n\r]+\n?\r?", "").Replace("\r", "").Replace("\n", "").Replace(@"\", "");
                if (account.Replace(" ", "").Trim() == "")
                    continue;

                //Смотрим нужно ли грабить задание или нет
                string activ = new Regex("activ:([a-z]+);").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim();
                if (activ == "" || activ == "false")
                    continue;

                //Токены и ID
                string Token = new Regex("UsrerToken:([a-zA-Z0-9]+);").Match(account.Replace(" ", "")).Groups[1].Value;
                string ModToken = new Regex("ModerationToken:([a-zA-Z0-9]+);").Match(account.Replace(" ", "")).Groups[1].Value;
                string userID = new engine.VK_API.UserGet().get(Token);
                string ModID = new engine.VK_API.UserGet().get(ModToken);
                string ID = new Regex("id:([^;]+);").Match(account.Replace(" ", "")).Groups[1].Value.Trim();

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Список групп куда грабить и список URL для загрузки изображения
                List<InfoClass.GroupPost> Gpost = new List<InfoClass.GroupPost> { };
                foreach (string gPost in new Regex("grouppost:{([-0-9,]+)};").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Split(','))
                {
                    //Добовляем в List
                    Gpost.Add(new InfoClass.GroupPost
                    {
                        GroupID = gPost.Trim(),
                        UploadURL = new engine.VK_API.UploadURL().get(Token, gPost),
                        ModerationUploadURL = new engine.VK_API.UploadURL().get(ModToken, gPost)
                    });
                }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Грузим ключи если они доступны
                List<string> key = new List<string> { };
                foreach (string s1 in new Regex("GroupKey:{([A-Za-z-0-9,_-]+)};").Match(account.Replace(" ", "")).Groups[1].Value.Split(','))
                {
                    if (File.Exists(conf.DirKey + s1))
                    {
                        foreach (string s2 in File.ReadLines(conf.DirKey + s1))
                        {
                            key.Add(s2.Trim());
                        }
                    }
                }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Грузим теги если они доступны
                List<string> tag = new List<string> { };
                if (File.Exists(conf.DirTag + ID))
                {
                    foreach (string s in File.ReadLines(conf.DirTag + ID))
                    {
                        tag.Add(s.ToLower().Trim());
                    }
                }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Загружаем данные для групп
                List<InfoClass.GroupList> Glist = new List<InfoClass.GroupList> { };
                foreach (string gListID in new Regex("GroupList:{([a-zA-Z0-9-_,]+)};").Match(account.Replace(" ", "")).Groups[1].Value.Split(','))
                {
                    if (File.Exists(conf.DirGroupList + gListID))
                    {
                        foreach (string gList in Regex.Replace(Regex.Replace(File.ReadAllText(conf.DirGroupList + gListID), @"/\*[^\*]+\*/", ""), "//[^\n\r]+\n?\r?", "").ToLower().Replace(" ", "").Replace("\r", "").Split('\n'))
                        {
                            if (gList.Trim() == "")
                                continue;

                            GroupCollection g = new Regex("group:'([-0-9]+)',{photo=([a-z]+),text=([a-z]+),poll=([a-z]+),audio=([a-z]+),video=([a-z]+),break=([a-z]+),attachmentsnullblock=([a-z]+),moderationnews=([a-z]+)};").Match(gList).Groups;
                            int lastTime = 0;

                            //Если нету ID откуда брать то и остальное не нужно
                            if (g[1].Value.Replace(" ", "").Trim() == "")
                                continue;

                            ////////////////////////////////////////////////////////////////////

                            if (File.Exists(conf.DirLastTime + ID))
                            {
                                foreach (string last in File.ReadAllLines(conf.DirLastTime + ID))
                                {
                                    if ((new Regex(g[1].Value + ":[0-9]+").Match(last)).Success)
                                    {
                                        lastTime = int.Parse(new Regex(g[1].Value + ":([0-9]+)").Match(last).Groups[1].Value);
//.........这里部分代码省略.........
开发者ID:korner-brazers,项目名称:VKNext,代码行数:101,代码来源:LoadConf.cs

示例13: MainForm_Load


//.........这里部分代码省略.........
                        else
                        {
                            NetEx.Transfer.DownloadFile(srv, externDbPath);
                            if (File.Exists(externDbPath))
                                length = new FileInfo(externDbPath).Length;
                        }
                        if (File.Exists(externDbPath) && length > 0x6000)
                            break;
                    }

                    // Merge databases
                    _appsDbSections = Ini.GetSections(AppsDbPath);
                    if (File.Exists(externDbPath))
                    {
                        using (var p = Compaction.Zip7Helper.Unzip(externDbPath, tmpAppsDbDir))
                            if (!p?.HasExited == true)
                                p?.WaitForExit();
                        File.Delete(externDbPath);
                        externDbPath = tmpAppsDbPath;
                        if (File.Exists(externDbPath))
                        {
                            foreach (var section in Ini.GetSections(externDbPath))
                            {
                                if (_appsDbSections.ContainsEx(section) || section.ContainsEx("PortableApps.com", "ByPortableApps"))
                                    continue;
                                var nam = Ini.Read(section, "Name", externDbPath);
                                if (string.IsNullOrWhiteSpace(nam) || nam.ContainsEx("jPortable Launcher"))
                                    continue;
                                if (!nam.StartsWithEx("jPortable", "PortableApps.com"))
                                {
                                    var tmp = new Regex(", Portable Edition|Portable64|Portable", RegexOptions.IgnoreCase).Replace(nam, string.Empty);
                                    tmp = Regex.Replace(tmp, @"\s+", " ");
                                    if (!string.IsNullOrWhiteSpace(tmp) && tmp != nam)
                                        nam = tmp.Trim().TrimEnd(',');
                                }
                                var des = Ini.Read(section, "Description", externDbPath);
                                if (string.IsNullOrWhiteSpace(des))
                                    continue;
                                var cat = Ini.Read(section, "Category", externDbPath);
                                if (string.IsNullOrWhiteSpace(cat))
                                    continue;
                                var ver = Ini.Read(section, "DisplayVersion", externDbPath);
                                if (string.IsNullOrWhiteSpace(ver))
                                    continue;
                                var pat = Ini.Read(section, "DownloadPath", externDbPath);
                                pat = $"{(string.IsNullOrWhiteSpace(pat) ? "http://downloads.sourceforge.net/portableapps" : pat)}/{Ini.Read(section, "DownloadFile", externDbPath)}";
                                if (!pat.EndsWithEx(".paf.exe"))
                                    continue;
                                var has = Ini.Read(section, "Hash", externDbPath);
                                if (string.IsNullOrWhiteSpace(has))
                                    continue;
                                var phs = new Dictionary<string, List<string>>();
                                foreach (var lang in Lang.GetText("availableLangs").Split(','))
                                {
                                    if (string.IsNullOrWhiteSpace(lang))
                                        continue;
                                    var tmpFile = Ini.Read(section, $"DownloadFile_{lang}", externDbPath);
                                    if (string.IsNullOrWhiteSpace(tmpFile))
                                        continue;
                                    var tmphash = Ini.Read(section, $"Hash_{lang}", externDbPath);
                                    if (string.IsNullOrWhiteSpace(tmphash) || !string.IsNullOrWhiteSpace(tmphash) && tmphash == has)
                                        continue;
                                    var tmpPath = Ini.Read(section, "DownloadPath", externDbPath);
                                    tmpFile = $"{(string.IsNullOrWhiteSpace(tmpPath) ? "http://downloads.sourceforge.net/portableapps" : tmpPath)}/{tmpFile}";
                                    phs.Add(lang, new List<string> { tmpFile, tmphash });
                                }
开发者ID:Si13n7,项目名称:PortableAppsSuite,代码行数:67,代码来源:MainForm.cs

示例14: RemoveInvalidCharacters

 /// <summary>
 /// Removes invalid characters from the provided displayname.
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static string RemoveInvalidCharacters(string s)
 {
     // NOTE: changing this code requires a change in RemoveInvalidCharacters, GetNoAccents javascript functions in SN.ContentName.js, in order that these work in accordance
     var noaccents = GetNoAccents(s);
     noaccents = new Regex(RepositoryPath.InvalidNameCharsPattern).Replace(noaccents, ContentNamingHelper.PlaceholderSymbol.ToString());
     // space is also removed
     noaccents = noaccents.Replace(' ', ContentNamingHelper.PlaceholderSymbol);
     // '-' should not be followed by another '-'
     noaccents = new Regex(ContentNamingHelper.PlaceholderSymbol + "{2,}").Replace(noaccents, ContentNamingHelper.PlaceholderSymbol.ToString());
     noaccents = noaccents.Trim(ContentNamingHelper.PlaceholderSymbol);
     return noaccents;
 }
开发者ID:jhuntsman,项目名称:FlexNet,代码行数:17,代码来源:ContentNamingHelper.cs

示例15: LoadModFromZip

        ModData LoadModFromZip(string zipFileFullName)
        {
            log.Debug("Loading '{0}'", Path.GetFileName(zipFileFullName));

            ModData detail = new ModData();
            string tempDir = Path.Combine(Path.GetTempPath(), "mc", Guid.NewGuid().ToString());

            detail.FullPath = zipFileFullName;
            detail.FileSize = new FileInfo(zipFileFullName).Length;
            detail.Hash = new FileInfo(zipFileFullName).CalcMD5();

            // Fallback title
            detail.Title = Path.GetFileNameWithoutExtension(detail.FileName).ToLowerInvariant();
            detail.Title = detail.Title.ReplaceEx(new string[] { "aaa_", "zzz_", "aaa", "zzz" }, string.Empty);

            // Make any word begin with upercase letter
            detail.Title = Regex.Replace(detail.Title, @"((?<=\p{Ll})\p{Lu})|((?!\A)\p{Lu}(?>\p{Ll}))", " $0");

            // Remove duplicate spaces
            detail.Title.Normalize();

            try
            {
                Directory.CreateDirectory(tempDir);

                if (Unzip(zipFileFullName, tempDir, new string[] { MOD_DESC_FILENAME }, true, true))
                {
                    StringBuilder sb = new StringBuilder();

                    // Clear comments, cause they are often not wellformed
                    foreach (string line in File.ReadAllLines(Path.Combine(tempDir, MOD_DESC_FILENAME)))
                    {
                        string currentLine = new Regex("(?s)<!--.*?-->", RegexOptions.Compiled).Replace(line, "");
                        currentLine = new Regex("[&]+", RegexOptions.Compiled).Replace(line, "");

                        if (string.IsNullOrEmpty(currentLine))
                            continue;

                        sb.AppendLine(currentLine.Trim());
                    }

                    try
                    {
                        XmlReaderSettings settings = new XmlReaderSettings();

                        using (TextReader txtReader = new StringReader(sb.ToString()))
                        using (XmlReader reader = XmlReader.Create(txtReader, settings))
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.Load(reader);

                            detail.Title = doc.GetInnerTextNormalized(string.Format("/modDesc/title/{0}", "de"));
                            if (string.IsNullOrEmpty(detail.Title))
                                detail.Title = doc.GetInnerTextNormalized("modDesc/title/en");

                            detail.Description = doc.GetInnerTextNormalized(string.Format("/modDesc/description/{0}", "de"));
                            if (string.IsNullOrEmpty(detail.Description))
                                detail.Description = doc.GetInnerTextNormalized("modDesc/description/en");

                            detail.Author = doc.GetInnerTextNormalized("/modDesc/author");
                            detail.Version = doc.GetInnerTextNormalized("/modDesc/version");
                            detail.IsMultiplayerReady = Convert.ToBoolean(doc.GetInnerTextSave("/modDesc/multiplayer/@supported"));

                            //lock (locker)
                            //{
                            //detail.Image = LoadBitmap(zipFileFullName, tempDir, doc.GetInnerTextSave("/modDesc/iconFilename"));
                            //}

                            foreach (XmlNode node in doc.SelectNodes("/modDesc/storeItems/storeItem"))
                            {
                                StoreItemData shopItem = new StoreItemData();

                                shopItem.Name = node.GetInnerTextSave(string.Format("{0}/name", "de"));
                                if (string.IsNullOrEmpty(shopItem.Name))
                                    shopItem.Name = node.GetInnerTextSave("en/name");

                                shopItem.Price = Convert.ToDouble(node.GetInnerTextSave("price"));
                                shopItem.Upkeep = Convert.ToDouble(node.GetInnerTextSave("dailyUpkeep"));
                                shopItem.MachineType = node.GetInnerTextSave("machineType");
                                shopItem.Brand = node.GetInnerTextSave("brand");

                                shopItem.Description = node.GetInnerTextSave(string.Format("{0}/description", "de"));
                                if (string.IsNullOrEmpty(shopItem.Description))
                                    shopItem.Description = node.GetInnerTextSave("en/description");

                                shopItem.Description = shopItem.Description.Replace("\r\n", " ");

                                //shopItem.IsMultiplayerReady = Convert.ToBoolean(node.GetInnerTextSave("/modDesc/multiplayer/@supported"));
                                shopItem.XmlFileName = node.GetInnerTextSave("xmlFilename");
                                shopItem.ImagePath = node.GetInnerTextSave("image/@active");
                                shopItem.BrandImagePath = node.GetInnerTextSave("image/@brand");

                                lock (locker)
                                {
                                    if (detail.Image == null)
                                    {
                                        detail.Image = LoadBitmap(zipFileFullName, tempDir, shopItem.ImagePath);
                                        shopItem.Image = detail.Image;
                                    }
                                    else
//.........这里部分代码省略.........
开发者ID:Fox-Alpha,项目名称:ModCommander,代码行数:101,代码来源:ModExtractor.cs


注:本文中的System.Text.RegularExpressions.Regex.Trim方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。