private void InjectIni(string sourceFilePath, string sectionName, IniParser.Model.SectionData translatedSectionData) { var stringIniParser = new IniParser.FileIniDataParser(); stringIniParser.Parser.Configuration.AllowDuplicateKeys = true; stringIniParser.Parser.Configuration.SkipInvalidLines = true; stringIniParser.Parser.Configuration.CommentRegex = new System.Text.RegularExpressions.Regex("^;.*"); var stringInidata = stringIniParser.ReadFile(sourceFilePath, Encoding.Default); foreach (var sectionKey in translatedSectionData.Keys) { var section = sectionKey.KeyName.Split('@').First(); var key = sectionKey.KeyName.Split('@').Last(); var value = sectionKey.Value.SanitizeQuotes().Trim(); if (this.RemoveSpecialsChars) { value = value.DeleteAccentAndSpecialsChar().RemoveDiacritics(); } if (stringInidata.Sections.Any(s => s.SectionName == section)) { var iniSectionData = stringInidata.Sections.GetSectionData(section); if (iniSectionData.Keys.Any(k => k.KeyName == key)) { iniSectionData.Keys.GetKeyData(key).Value = value; } } } stringIniParser.WriteFile(sourceFilePath, stringInidata, Encoding.Default); }
public static void ReadConfig() { //读取配置 var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile(".\\config.ini"); //加载配置 ClassCount = int.Parse(data["option"]["ClassCount"]); DayPerWeek = int.Parse(data["option"]["DayPerWeek"]); LessonPerMorning = int.Parse(data["option"]["LessonPerMorning"]); LessonPerDay = int.Parse(data["option"]["LessonPerDay"]); LessonPerForenoon = int.Parse(data["option"]["LessonPerForenoon"]); LessonPerNight = int.Parse(data["option"]["LessonPerNight"]); PopulationSize = int.Parse(data["runtime"]["PopulationSize"]); TotalFitness = PopulationSize * (PopulationSize + 1) / 2; TotalEvolveTime = int.Parse(data["runtime"]["TotalEvolveTime"]); MutateRate = int.Parse(data["runtime"]["MutateRate"]); CrossRate = int.Parse(data["runtime"]["CrossRate"]); }
/// <summary> /// Parse the team name, game name, etc, out of a given config file using the IniParser. /// </summary> /// <param name="configFilePath"></param> /// <returns></returns> private string GetParameterFromConfig(string param, string configFilePath) { IniParser.FileIniDataParser parser = new IniParser.FileIniDataParser(); IniParser.Model.IniData configData = parser.ReadFile(configFilePath); IniParser.Model.KeyDataCollection gameInfo = configData[gameInfoSection]; return(gameInfo.GetKeyData(param).Value); }
public ConfigLoader(string configFilePath = null) { if (string.IsNullOrEmpty(configFilePath)) { configFilePath = AppDomain.CurrentDomain.BaseDirectory + "config.ini"; if (!File.Exists(configFilePath)) { throw new Exception("Could not find configuration file"); } } Logger.Info("Loading configuration from: " + configFilePath); try { var parser = new IniParser.FileIniDataParser(); ConfigData = parser.ReadFile(configFilePath); } catch (FileNotFoundException) { throw new Exception("Could not find configuration file at: " + configFilePath); } catch (ParsingException e) { throw new Exception("Unable to parse configuration file [" + configFilePath + "]: " + e.Message); } foreach (var section in ConfigData.Sections) foreach (var item in section.Keys) { item.Value = item.Value.Replace("{AppDir}", AppDomain.CurrentDomain.BaseDirectory); item.Value = item.Value.Replace("{AppDataDir}", AppDomain.CurrentDomain.BaseDirectory); } }
/// <summary> /// 保存配置 /// </summary> public static void Save() { if (!File.Exists("Data\\TUNTAP.ini")) { File.WriteAllBytes("Data\\TUNTAP.ini", Properties.Resources.defaultTUNTAP); } var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile("Data\\TUNTAP.ini"); data["Generic"]["Address"] = Global.TUNTAP.Address.ToString(); data["Generic"]["Netmask"] = Global.TUNTAP.Netmask.ToString(); data["Generic"]["Gateway"] = Global.TUNTAP.Gateway.ToString(); var dns = ""; foreach (var ip in Global.TUNTAP.DNS) { dns += ip.ToString(); dns += ','; } dns = dns.Trim(); data["Generic"]["DNS"] = dns.Substring(0, dns.Length - 1); parser.WriteFile("Data\\TUNTAP.ini", data); File.WriteAllText("Data\\Servers.json", Newtonsoft.Json.JsonConvert.SerializeObject(Global.Servers)); }
/// <summary> /// Reads the WireGuard service configuration from file. /// </summary> /// <param name="filePath">File path of WireGuard service configuration file.</param> /// <returns>Success status of reading from the WireGuard service configuration file.</returns> public bool ReadFromFile(string filePath) { if (!File.Exists(filePath)) { return(false); } var parser = new IniParser.FileIniDataParser(); var iniData = parser.ReadFile(filePath); Interface = new InterfaceProperties() { PrivateKey = iniData["Interface"]["PrivateKey"], Address = iniData["Interface"]["Address"], DNS = iniData["Interface"]["DNS"], }; Peer = new PeerProperties() { PublicKey = iniData["Peer"]["PublicKey"], AllowedIPs = iniData["Peer"]["AllowedIPs"], Endpoint = iniData["Peer"]["Endpoint"], }; return(true); }
/// <summary> /// Reads INI file and get the SCRIPT/Version. If INI Value is not present then Resource Min Version is returned. /// </summary> /// <returns>Version Representing the script version</returns> public static Version GetScriptVersion() { string iniFile = AppCommon.Instance.AppIniFile; string strVersion = string.Empty; if (File.Exists(iniFile)) { try { var ini = new IniParser.FileIniDataParser(); IniParser.Model.IniData data = ini.ReadFile(iniFile); strVersion = data[Properties.Settings.Default.IniScriptSection][Properties.Settings.Default.IniScriptVersion]; } catch (Exception) { strVersion = string.Empty; } } Version ver; if (string.IsNullOrEmpty(strVersion)) { ver = AppCommon.Instance.DefaultMinVersion; } else { if (!Version.TryParse(strVersion, out ver)) { ver = AppCommon.Instance.DefaultMinVersion; } } return(ver); }
static GiphyBot() { var parser = new IniParser.FileIniDataParser(); var ini = parser.ReadFile("bots/giphybot.ini"); ApiKey = ini.Global["API_KEY"]; }
/// <summary> /// Gets if the AutoHotkey Script is running based upon the ini load_state setting /// </summary> /// <returns> /// True if the script is running; Otherwise false /// </returns> public static bool GetScriptIsRunning() { string iniFile = AppCommon.Instance.AppIniFile; bool retval = false; if (File.Exists(iniFile)) { var ini = new IniParser.FileIniDataParser(); IniParser.Model.IniData data = ini.ReadFile(iniFile); string state = data[Properties.Settings.Default.IniScriptSection][Properties.Settings.Default.IniScriptLoadState]; bool Parsed = false; // attempt to parse as boolean if that does not work attempt to parse as int if (bool.TryParse(state, out retval)) { Parsed = true; } if (Parsed == false) { int iState = 0; if (int.TryParse(state, out iState)) { retval = (iState > 0); } } } return(retval); }
public static PrebuildConfig getDataForBuild(gitlab_ci_runner.api.BuildInfo b) { if (!isConfigured()) { throw new NotImplementedException("Situation when no configuration file is provided is not supported yet. Make sure that runner.cfg exists at the file location."); } IniParser.FileIniDataParser ini = new IniParser.FileIniDataParser(); IniParser.Model.IniData data = ini.ReadFile(confPath); IniParser.Model.SectionData section = null; foreach (var sect in data.Sections) { string[] projectIdentifiers = sect.SectionName.Split(new char[] {'|'} ); foreach(var p in projectIdentifiers) { string[] components = p.Split( new char[] {'='} ); if (components.Length == 2) { switch (components[0]) { case "id": if (Convert.ToInt32(components[1]) == b.project_id) { section = sect; } break; case "name": if (components[1] == b.project_name || components[1] == Regex.Replace(b.project_name, @"\s+", "")) { section = sect; } break; default: throw new Exception(String.Format("Cannot parse the {0} due to unknown project filter {1}", confPath, p)); } } else { if (p == "*") { section = sect; } else { if (p!="main") throw new Exception(String.Format("Cannot parse the {0} while searching for the project prebuild steps commands. Section {1} cannot be recognized.", confPath, p)); } } if (section != null) { break; } } if (section != null) { break; } } return new PrebuildConfig(b, section); }
public void InjectTransifexFile() { // parcours les fichier puis essaye de retrouver la partie correspondante dans le fichier de traduction if (!File.Exists(this.TransifexFilePath)) { throw new InvalidOperationException("No transifex file"); } var type = DemocracyStringHandling.DetectFileType(this.TransifexFilePath); if (type == FileType.MainSentences) { InjectMain(); } else if (type == FileType.Mods) { var transifexFileParser = new IniParser.FileIniDataParser(); var transifexInidata = transifexFileParser.ReadFile(this.TransifexFilePath, Encoding.UTF8); var modPath = transifexInidata.Sections.Where(s => s.SectionName.Contains("Mod__")).First().SectionName.Replace("Mod__", ""); InjectMod(modPath); } else { //throw new InvalidOperationException("File not currently supported"); } }
/// <summary> /// Gets IP address from config file. /// </summary> /// <param name="type">IP version address to be returned (IPv4 or IPv6).</param> /// <returns>Address of requested IP version.</returns> private string GetAddressFromConfig(AddressType type) { string filePath = ProductConstants.FirefoxPrivateNetworkConfFile; if (File.Exists(filePath)) { var parser = new IniParser.FileIniDataParser(); var iniData = parser.ReadFile(filePath); string address = iniData["Interface"]["Address"]; string[] addresses = address.Split(','); IPAddress ipAddress; foreach (var addr in addresses) { if (addr == string.Empty) { continue; } bool parsedIP = IPAddress.TryParse(addr.Split('/')[0], out ipAddress); if (parsedIP && CheckCorrectAddress(type, ipAddress)) { return(addr); } } } return(string.Empty); }
//read the games config file and load the assets /// <param name="directory"> directory to load game assets from</param> public void LoadAssets(string directory) { IniParser.FileIniDataParser parser = new IniParser.FileIniDataParser(); IniParser.Model.IniData configData = parser.ReadFile(directory); IniParser.Model.KeyDataCollection gameInfo = configData[assetSection]; string teamName = gameInfo.GetKeyData(teamSection).Value; string gameName = gameInfo.GetKeyData(nameSection).Value; }
static CleverBot() { var parser = new IniParser.FileIniDataParser(); var ini = parser.ReadFile("bots/cleverbot.ini"); ApiUser = ini.Global["API_USER"]; ApiKey = ini.Global["API_KEY"]; }
static ImgurBot() { var parser = new IniParser.FileIniDataParser(); var ini = parser.ReadFile("bots/imgurbot.ini"); ClientID = ini.Global["CLIENT_ID"]; ClientSecret = ini.Global["CLIENT_SECRET"]; }
public PrefForm(epsexecForm main) { configPath = main.configPath; InitializeComponent(); mainForm = main; IniParser.FileIniDataParser parser = new IniParser.FileIniDataParser(); if (!File.Exists(configPath)) { File.WriteAllLines(configPath, new string[] { "; Settings", "; Feel free to edit this", "; Do not get rid of any setting.set it to true / false", "", "ignore_ip_warn = true", "ignore_not_connected_warn = false", "always_on_top = false", "hide_in_taskbar = false", "dont_use_paexec_on_remote_pc = false" }); } IniParser.Model.IniData data = parser.ReadFile(configPath); ignoreEmptyIpBox.Checked = Boolean.Parse(data.GetKey("ignore_ip_warn")); ignoreNotConnectedBox.Checked = Boolean.Parse(data.GetKey("ignore_not_connected_warn")); this.alwaysOnTopBox.Checked = Boolean.Parse(data.GetKey("always_on_top")); hideInTaskbarBox.Checked = Boolean.Parse(data.GetKey("hide_in_taskbar")); noPaexecBox.Checked = Boolean.Parse(data.GetKey("dont_use_paexec_on_remote_pc")); if (mainForm.ignoreIpEmpty != ignoreEmptyIpBox.Checked) { mainForm.ignoreIpEmpty = ignoreEmptyIpBox.Checked; } if (mainForm.ignoreNotConnected != ignoreNotConnectedBox.Checked) { mainForm.ignoreNotConnected = ignoreNotConnectedBox.Checked; } if (mainForm.alwaysOnTopToolStripMenuItem.Checked != alwaysOnTopBox.Checked) { mainForm.alwaysOnTopToolStripMenuItem.Checked = alwaysOnTopBox.Checked; } if (mainForm.hideInTaskbarToolStripMenuItem.Checked != hideInTaskbarBox.Checked) { mainForm.hideInTaskbarToolStripMenuItem.Checked = hideInTaskbarBox.Checked; } if (mainForm.noPaExec != noPaexecBox.Checked) { mainForm.noPaExec = noPaexecBox.Checked; } }
/// <summary> /// Write IPv4 and IPv6 addresses to settings file from config if they are not already there. /// </summary> public void MigrateConfigAddressToSettingsFile() { var filename = ProductConstants.SettingsFile; bool overwriteFile = false; if (!File.Exists(filename)) { return; } var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile(filename); if (data.Sections.ContainsSection("Network")) { var networkData = data.Sections.GetSectionData("Network"); string ipAddress; if (!networkData.Keys.ContainsKey("IPv4Address") || data["Network"]["IPv4Address"] == string.Empty) { ipAddress = GetAddressFromConfig(AddressType.IPv4); if (ipAddress != string.Empty) { data["Network"]["IPv4Address"] = ipAddress; overwriteFile = true; } } if (!networkData.Keys.ContainsKey("IPv6Address") || data["Network"]["IPv6Address"] == string.Empty) { ipAddress = GetAddressFromConfig(AddressType.IPv6); if (ipAddress != string.Empty) { data["Network"]["IPv6Address"] = ipAddress; overwriteFile = true; } } if (overwriteFile) { try { FileInfo file = new FileInfo(filename); Directory.CreateDirectory(file.Directory.FullName); File.WriteAllText(filename, data.ToString()); } catch (Exception e) { ErrorHandling.ErrorHandler.Handle(e, ErrorHandling.LogLevel.Error); return; } } } }
public Logger(String IniFile) { var parser = new IniParser.FileIniDataParser(); data = parser.ReadFile(IniFile); interval = Convert.ToInt32(data ["MAIN"] ["interval"]); sqlQuery("CREATE TABLE IF NOT EXISTS log (id SERIAL PRIMARY KEY, timestamp TIMESTAMP WITH TIME ZONE, object TEXT, value REAL);"); }
public void Load() { var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile(Program.PATH + "settings.ini"); Random = bool.Parse(data["settings"]["random"]); IntervalId = int.Parse(data["settings"]["speed"]); UseSubdirectories = bool.Parse(data["settings"]["subdirectories"]); Directory = data["settings"]["directory"]; }
protected static void LoadCec() { var p = new IniParser.FileIniDataParser(); try { config = p.ReadFile(".cec/config"); } catch { config = new IniData(); } }
static RedditBot() { var parser = new IniParser.FileIniDataParser(); var ini = parser.ReadFile("bots/redditbot.ini"); Username = ini.Global["USERNAME"]; Password = ini.Global["PASSWORD"]; ClientID = ini.Global["CLIENT_ID"]; ClientSecret = ini.Global["CLIENT_SECRET"]; RedirectUri = ini.Global["REDIRECT_URI"]; }
public static string ReadModEngineDirectory(string gameDirectory) { gameDirectory = gameDirectory.TrimEnd('\\'); string iniPath = $@"{gameDirectory}\modengine.ini"; var parser = new IniParser.FileIniDataParser(); IniParser.Model.IniData ini = parser.ReadFile(iniPath); string modDirectory = ini["files"]["modOverrideDirectory"].Trim('"').TrimStart('\\'); return($@"{gameDirectory}\{modDirectory}"); }
public void Save() { var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile(Program.PATH + "settings.ini"); data["settings"]["random"] = Random.ToString(); data["settings"]["speed"] = IntervalId.ToString(); data["settings"]["subdirectories"] = UseSubdirectories.ToString(); data["settings"]["directory"] = Directory; parser.WriteFile(Program.PATH + "settings.ini", data); }
private string GetCurrentProfile() { string iniFile = AppCommon.Instance.SetingsIniFile; string retval = string.Empty; if (File.Exists(iniFile)) { var ini = new IniParser.FileIniDataParser(); IniParser.Model.IniData data = ini.ReadFile(iniFile); retval = data["PROFILE"]["current"]; } return(retval); }
/// <summary> /// Gets the Window Spy Location from Settings.ini, Apps, windowspy key /// </summary> /// <returns> /// The value from the ini file if it exist; Otherwise, empty string. /// </returns> /// <remarks> /// This Gives the user a way to set the Window Spy location if it is not found at its default location. /// </remarks> public static string GetWindowSpyApp() { string iniFile = AppCommon.Instance.SetingsIniFile; string retval = string.Empty; if (File.Exists(iniFile)) { var ini = new IniParser.FileIniDataParser(); IniParser.Model.IniData data = ini.ReadFile(iniFile); retval = data[Properties.Settings.Default.IniSettingsAppSection][Properties.Settings.Default.IniSettingsAppWindowSpy]; } return(retval); }
/// <summary> /// Gets the Exit Code in the App ini for the writers last exit code; /// </summary> /// <returns></returns> public static int GetWriterExitReason() { string iniFile = AppCommon.Instance.AppIniFile; int Reason = 0; if (File.Exists(iniFile)) { var ini = new IniParser.FileIniDataParser(); IniParser.Model.IniData data = ini.ReadFile(iniFile); string iniReason = data[Properties.Settings.Default.IniWriterSection][Properties.Settings.Default.IniWriterExitCode]; if (int.TryParse(iniReason, out Reason) == false) { Reason = 0; } } return(Reason); }
/// <summary> /// Gets the Path to the current running AutoHotkey Script /// </summary> /// <returns> /// Full Path to script; Otherwise empty string. /// </returns> public static string GetRunningScriptPath() { string iniFile = AppCommon.Instance.AppIniFile; string scriptPath = string.Empty; if (File.Exists(iniFile)) { var ini = new IniParser.FileIniDataParser(); IniParser.Model.IniData data = ini.ReadFile(iniFile); scriptPath = data[Properties.Settings.Default.IniScriptSection][Properties.Settings.Default.IniScriptPath]; } if (string.IsNullOrEmpty(scriptPath)) { return(string.Empty); } return(scriptPath); }
public CustomisationDownloader() { NoCommands = () => { return(!doUpload && !doDownload); }; var p = new IniParser.FileIniDataParser(); if (IsCec()) { if (File.Exists(".cec/" + ShortName)) { custdlConfig = p.ReadFile(".cec/" + ShortName); } else { custdlConfig = new IniData(); p.WriteFile(".cec/" + ShortName, custdlConfig); } } }
/// <summary> /// 保存到文件 /// </summary> public static void SaveToFile() { var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile("x2tap.ini"); data["x2tap"]["v2rayLoggingLevel"] = Global.Config.V2RayLoggingLevel.ToString(); data["TUNTAP"]["Address"] = Global.Config.TUNTAP.Address; data["TUNTAP"]["Netmask"] = Global.Config.TUNTAP.Netmask; data["TUNTAP"]["Gateway"] = Global.Config.TUNTAP.Gateway; data["TUNTAP"]["DNS"] = Global.Config.TUNTAP.DNS; data["TUNTAP"]["UseCustomDNS"] = Global.Config.TUNTAP.UseCustomDNS.ToString(); parser.WriteFile("x2tap.ini", data); File.WriteAllText("SubscriptionLinks.json", Newtonsoft.Json.JsonConvert.SerializeObject(Global.SubscriptionLinks)); File.WriteAllText("v2ray.json", Newtonsoft.Json.JsonConvert.SerializeObject(Global.V2RayProxies)); File.WriteAllText("Shadowsocks.json", Newtonsoft.Json.JsonConvert.SerializeObject(Global.ShadowsocksProxies)); File.WriteAllText("ShadowsocksR.json", Newtonsoft.Json.JsonConvert.SerializeObject(Global.ShadowsocksRProxies)); File.WriteAllText("ExceptionIPs.json", Newtonsoft.Json.JsonConvert.SerializeObject(Global.ExceptionIPs)); }
private bool SaveLibFromIni() { var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile("Lib2.ini"); foreach (var section in data.Sections) { var book = new Books { Isbn = section.SectionName, Title = data[section.SectionName]["Title"], Author = data[section.SectionName]["Author"], PublicationDate = data[section.SectionName]["PublicationDate"], Annotation = data[section.SectionName]["Annotation"] }; _books.Add(book); } return(true); }
/// <summary> /// 初始化配置 /// </summary> public static void Init() { if (File.Exists("Data\\TUNTAP.ini")) { var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile("Data\\TUNTAP.ini"); if (IPAddress.TryParse(data["Generic"]["Address"], out var address)) { Global.TUNTAP.Address = address; } if (IPAddress.TryParse(data["Generic"]["Netmask"], out var netmask)) { Global.TUNTAP.Netmask = netmask; } if (IPAddress.TryParse(data["Generic"]["Gateway"], out var gateway)) { Global.TUNTAP.Gateway = gateway; } var dns = new List <IPAddress>(); foreach (var ip in data["Generic"]["DNS"].Split(',')) { if (IPAddress.TryParse(ip, out var value)) { dns.Add(value); } } if (dns.Count > 0) { Global.TUNTAP.DNS = dns; } } if (File.Exists("Data\\Servers.json")) { Global.Servers = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Objects.Server> >(File.ReadAllText("Data\\Servers.json")); } }
private bool WriteBookToIni() { var parser = new IniParser.FileIniDataParser(); var data = parser.ReadFile("Library.ini"); foreach (var book in _books) { //Add a new selection and some keys data.Sections.AddSection(book.Isbn); data[book.Isbn].AddKey("Author", book.Author); data[book.Isbn].AddKey("Title", book.Title); //data[book.ISBN].AddKey("PublicationDate", book.PublicationDate.ToString("d")); data[book.Isbn].AddKey("PublicationDate", book.PublicationDate); data[book.Isbn].AddKey("Annotation", book.Annotation); parser.WriteFile("Library.ini", data); } return(true); }