public void DisallowsDuplicateSection() { var iniFile = new IniFile(new Sentence(), new IniSettings()); iniFile.AddSection("foo"); iniFile.AddSection("foo"); }
public void MergesDuplicateSection() { var iniFile = new IniFile(new Sentence(), new IniSettings { DuplicateSectionHandling = DuplicateSectionHandling.Merge }); iniFile.AddSection("foo"); iniFile.AddSection("foo"); Assert.IsTrue(iniFile.Sections.Count() == 1); Assert.IsTrue(iniFile.Sections.Count(x => x == "foo") == 1); }
public static string GetCheckFirstKeyFromSection(string filePath, string _section, string saveDefaultKey = null) { string keyReturn = null; IniFile ini = new IniFile(filePath); var sect = ini.GetSection(_section); LogUser Log = new LogUser(); if (sect == null) { sect = ini.AddSection(_section); if (saveDefaultKey != null) { sect.AddKey(saveDefaultKey); } ini.SaveShowMessage(); } if (sect.Keys.Count == 0 & saveDefaultKey != null) { sect.AddKey(saveDefaultKey); ini.SaveShowMessage(); } Log.Out(); SetFirstKeyFromSection(sect, ref keyReturn); return(keyReturn); }
public static string GetPathRejectFromFile() { IniFile ini = new IniFile(); ini.Load(PublicData.configFile); var sect = ini.GetSection("brak"); if (sect == null) { sect = ini.AddSection("brak"); sect.AddKey(defaultPathReject); } if (sect.Keys.Count == 0) { sect.AddKey(defaultPathReject); } ini.SaveShowMessage(); var keys = sect.Keys; string pathReject = defaultPathReject; foreach (IniFile.IniSection.IniKey key in keys) { pathReject = key.Name; break; } return(pathReject); }
public void RendersIniWithoutFormattingOptions() { var iniFile = new IniFile(); var bar = iniFile.AddSection("bar"); bar.AddComment("foo"); bar.AddProperty("baz", "baaz"); bar.AddProperty("qux", "quux"); var baar = iniFile.AddSection("baar"); baar.AddProperty("baaz", "baaaz"); baar.AddProperty("quux", "quuux"); var iniText = IniRenderer.Render(iniFile.GlobalSection, FormattingOptions.None); }
public static IniFile ReadString(string text) { if (string.IsNullOrWhiteSpace(text)) { return(new IniFile()); } var iniFile = new IniFile(); var lines = text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); for (int index = 0; index < lines.Length; index++) { var line = lines[index].Trim(); if (string.IsNullOrWhiteSpace(line) || line.StartsWith(";") || line.StartsWith("#")) { continue; } var sectionName = Regex.Match(line, @"(?<=^\[).*(?=\]$)").Value.Trim(); var section = iniFile.AddSection(sectionName); if (section != null) { continue; } iniFile.AddKey(line); } return(iniFile); }
public void IniFile_DoubleLoad() { var file = new IniFile(); file.AddSection("S").AddProperty("K", "V"); Assert.AreEqual(1, file.Sections.Count); Assert.AreEqual("S", file.Sections[0].Name); Assert.AreEqual(1, file.Sections[0].Properties.Count); Assert.AreEqual("K", file.Sections[0].Properties[0].Name); Assert.AreEqual("V", file.Sections[0].Properties[0].Value); file.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"Test.IniFile.Basic.ini")); Assert.AreEqual(2, file.Sections.Count); Assert.AreEqual("Section 1", file.Sections[0].Name); Assert.AreEqual("Section2", file.Sections[1].Name); Assert.AreEqual(2, file.Sections[0].Properties.Count); Assert.AreEqual("Key11", file.Sections[0].Properties[0].Name); Assert.AreEqual("Value11", file.Sections[0].Properties[0].Value); Assert.AreEqual("Key12", file.Sections[0].Properties[1].Name); Assert.AreEqual("Value12", file.Sections[0].Properties[1].Value); Assert.AreEqual(3, file.Sections[1].Properties.Count); Assert.AreEqual("Key21", file.Sections[1].Properties[0].Name); Assert.AreEqual("Value 21", file.Sections[1].Properties[0].Value); Assert.AreEqual("Key22", file.Sections[1].Properties[1].Name); Assert.AreEqual("Value 22", file.Sections[1].Properties[1].Value); Assert.AreEqual("Key23", file.Sections[1].Properties[2].Name); Assert.AreEqual("Value 23", file.Sections[1].Properties[2].Value); }
void addSection() { ExtendedTreeNode addSection = new ExtendedTreeNode(String.Format("NewSection{0}", secNumber), 0); iniSectionTreeView.Nodes.Add(addSection); ini.AddSection(addSection.Text); secNumber++; }
public void Ini_Save(string file, string section, string key, string value) { IniFile pIni = new IniFile(file); pIni.AddSection(section); pIni.DeleteKey(key, section); pIni.AddKey(key, value, section); pIni.Save(); }
private void WriteIni() { gameOptionPresetsIni = new IniFile(); int i = 0; var definitionsSection = new IniSection(PresetDefinitionsSectionName); gameOptionPresetsIni.AddSection(definitionsSection); foreach (var kvp in presets) { definitionsSection.SetStringValue(i.ToString(), kvp.Value.ProfileName); var presetSection = new IniSection(kvp.Value.ProfileName); kvp.Value.Write(presetSection); gameOptionPresetsIni.AddSection(presetSection); i++; } gameOptionPresetsIni.WriteIniFile(ProgramConstants.ClientUserFilesPath + IniFileName); }
public void Load(string fileName) { InfoFile = new IniFile(); InfoFile.Load(fileName); InfoSection = InfoFile.AddSection("info"); ProjectSection = InfoFile.AddSection("project"); time = Utils.i2t("0" + InfoSection["time"]); FilesCount = Convert.ToInt32("0" + InfoSection["FilesCount"]); AddedFilesCount = Convert.ToInt32("0" + InfoSection["AddedFilesCount"]); TotalSize = Convert.ToInt64("0" + InfoSection["TotalSize"]); TotalSizeAdded = Convert.ToInt64("0" + InfoSection["TotalSizeAdded"]); LogFile = InfoSection["LogFile"] + ""; if (!LogFile.Contains(":") && !LogFile.StartsWith("\\\\")) { LogFile = Path.GetDirectoryName(fileName) + "\\" + LogFile; } path = fileName; }
public void AddsSection() { var iniFile = new IniFile(new Sentence()); var s1 = iniFile.AddSection("foo"); Assert.AreEqual(s1, iniFile["foo"]); Assert.AreEqual(s1, ((dynamic)iniFile).foo); }
private IniFile.IniSection AddGetSection(IniFile ini, string name) { IniFile.IniSection section = ini.GetSection(name); if (section == null) { section = ini.AddSection(name); //ini.Save(path); } return(section); }
/// <summary> /// Writes the game command's information to an INI file. /// </summary> /// <param name="iniFile">The INI file.</param> public void WriteToIni(IniFile iniFile) { var section = new IniSection(ININame); section.SetStringValue("UIName", UIName); section.SetStringValue("Category", Category); section.SetStringValue("Description", Description); section.SetIntValue("DefaultKey", DefaultHotkey.GetTSEncoded()); iniFile.AddSection(section); }
private void button_CreateFileBrak_Click(object sender, EventArgs e) { string filePath = Path.Combine(PublicData.StartPath, "Забраковать" + textBoxFileEnd.Text); System.IO.File.CreateText(filePath).Close(); IniFile ini = new IniFile(); ini.Load(filePath); ini.AddSection("Брак"); ini.Save(filePath); }
private void button_CreateFileTestSound_Click(object sender, EventArgs e) { string filePath = Path.Combine(PublicData.StartPath, "Осциллограф" + textBoxFileEnd.Text); System.IO.File.CreateText(filePath).Close(); IniFile ini = new IniFile(); ini.Load(filePath); ini.AddSection("Осциллограф"); ini.Save(filePath); }
public static IniFile SaveAsIni(object obj, string section = "data") { var T = obj.GetType(); var F = T.GetProperties(); var ini = new IniFile(); var sec = ini.AddSection(section); foreach (var f in F) { var v = f.GetValue(obj, null); if (v is int) { sec[f.Name] = v + ""; } else if (v is Enum) { sec[f.Name] = v + ""; } else if (v is uint) { sec[f.Name] = v + ""; } else if (v is short) { sec[f.Name] = v + ""; } else if (v is ushort) { sec[f.Name] = v + ""; } else if (v is long) { sec[f.Name] = v + ""; } else if (v is ulong) { sec[f.Name] = v + ""; } else if (v is string) { sec[f.Name] = v + ""; } else if (v is char) { sec[f.Name] = v + ""; } else if (v is bool) { sec[f.Name] = v + ""; } } return(ini); }
static string GetStrForGenerator(string inc, string defaultTim, string defaultPat) { string section = "Generator"; string filend = new SavingManager().Key(Setting.FileEndOptions).Value; var fileOptions = PublicData.FindFileInTreeBySection(section); if (fileOptions == null) { fileOptions = Path.Combine(PublicData.RootPath, "options" + filend); try { File.CreateText(fileOptions).Close(); } catch (Exception ex) { ex.Show( ); } } IniFile ini = new IniFile(); ini.Load(fileOptions); string tim = ""; string pat = ""; try { tim = ini.GetSection(section).GetAddKey(inc + ".tim").Value; pat = ini.GetSection(section).GetAddKey(inc + ".pat").Value; } catch { var add = ini.AddSection(section); add.AddKey(inc + ".tim"); add.AddKey(inc + ".pat"); ini.SaveShowMessage(fileOptions); } if (tim == null || tim == "") { tim = defaultTim;//81 ini.SetKeyValue(section, inc + ".tim", defaultTim); ini.SaveShowMessage(fileOptions); } if (pat == null || pat == "") { pat = defaultPat;//3501 ini.SetKeyValue(section, inc + ".pat", defaultPat); ini.SaveShowMessage(fileOptions); } string str = "load tim " + tim + ";load pat " + pat + ";run;"; return(str); }
/// <summary> /// Writes build information into the specified file path. /// Erases the file first if it already exists. /// </summary> /// <param name="filePath">The file path.</param> public void Write(string filePath) { File.Delete(filePath); var iniFile = new IniFile(filePath); var versionSection = new IniSection(VERSION_SECTION); iniFile.AddSection(versionSection); ProductVersionInfo.Write(versionSection); var filesSection = new IniSection(FILES_SECTION); iniFile.AddSection(filesSection); for (int i = 0; i < FileInfos.Count; i++) { filesSection.SetStringValue(i.ToString(), FileInfos[i].GetString()); } iniFile.WriteIniFile(); }
public static IniFile ReadFromFile(string file) { if (string.IsNullOrWhiteSpace(file)) { return(null); } if (!File.Exists(file)) { return(new IniFile()); } var iniFile = new IniFile(); using (StreamReader reader = new StreamReader(file)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); if (string.IsNullOrWhiteSpace(line) || line.StartsWith(";") || line.StartsWith("#")) { continue; } var sectionName = Regex.Match(line, @"(?<=^\[).*(?=\]$)").Value.Trim(); var section = iniFile.AddSection(sectionName); if (section != null) { continue; } iniFile.AddKey(line); } reader.Close(); } return(iniFile); }
public string GetStr(string inc, string defaultTim, string defaultPat) { var fileOptions = PublicData.FindFileThroughTreeBySection("Generator"); IniFile ini = new IniFile(); ini.Load(fileOptions); string tim = ""; string pat = ""; try { tim = ini.GetSection("Generator").GetKey(inc + ".tim").Value; pat = ini.GetSection("Generator").GetKey(inc + ".pat").Value; } catch { var add = ini.AddSection("Generator"); add.AddKey(inc + ".tim"); add.AddKey(inc + ".pat"); ini.Save(fileOptions); } if (tim == null || tim == "") { tim = defaultTim;//81 ini.SetKeyValue("Generator", inc + ".tim", defaultTim); ini.Save(fileOptions); } if (pat == null || pat == "") { pat = defaultPat;//3501 ini.SetKeyValue("Generator", inc + ".pat", defaultPat); ini.Save(fileOptions); } string str = "load tim " + tim + ";load pat " + pat + ";run;"; return(str); }
/// <summary> /// Due to caching, this may not have been loaded on application start. /// This function provides the ability to load when needed. /// </summary> /// <returns></returns> private IniFile GetCustomMapIniFile() { if (customMapIni != null) { return(customMapIni); } customMapIni = new IniFile { FileName = customMapFilePath }; customMapIni.AddSection("Basic"); customMapIni.AddSection("Map"); customMapIni.AddSection("Waypoints"); customMapIni.AddSection("Preview"); customMapIni.AddSection("PreviewPack"); customMapIni.AddSection("ForcedOptions"); customMapIni.AddSection("ForcedSpawnIniOptions"); customMapIni.AllowNewSections = false; customMapIni.Parse(); return(customMapIni); }
private Task IniWritePresetList() { return(Task.Run(() => { /* * this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() => * { * this.list.ScrollIntoView(this.list.SelectedItem); * })); */ //파일이 존재하지 않으면? lock (lockObject) { //string strPath = System.IO.Directory.GetCurrentDirectory() + "\\presetlist.ini"; ini.IniWriteValue("common", "NumberOfPreset", presetList.Count().ToString()); for (int i = 0; i < presetList.Count(); i++) { string num = string.Format("Num{0:d2}", i + 1); //ini.IniWriteValue(num, "no", (i+1).ToString()); ini.IniWriteValue(num, "name", presetList[i].Name); ini.IniWriteValue(num, "time", presetList[i].Time.ToString()); ini.IniWriteValue(num, "pan", presetList[i].PanAbs.ToString()); ini.IniWriteValue(num, "tilt", presetList[i].TiltAbs.ToString()); ini.IniWriteValue(num, "zoom", presetList[i].Zoom.ToString()); ini.IniWriteValue(num, "focus", presetList[i].Focus.ToString()); } #if false IniFile ini = new IniFile(); if (bExists) { //파일이 이미 존재하는경우 ini.Load(strPath); ini.RemoveAllSections(); } for (int i = 0; i < this.presetList.Count(); i++) { string sectionName = "PRESET_" + i.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_ID).Value = presetList[i].ID.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_NAME).Value = presetList[i].Name.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_SEC).Value = presetList[i].Sec.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_X).Value = presetList[i].X.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_Y).Value = presetList[i].Y.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_ZOOM).Value = presetList[i].Zoom.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_GROUP).Value = presetList[i].Group.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_PANABS).Value = presetList[i].PanAbs.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_TILTABS).Value = presetList[i].TiltAbs.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_PANREL).Value = presetList[i].PanRel.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_TILTREL).Value = presetList[i].TiltRel.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_TARDIST).Value = presetList[i].TargetDistance.ToString(); ini.AddSection(sectionName).AddKey(PresetInfo.STR_TARLAT).Value = presetList[i].TargetLatitude; ini.AddSection(sectionName).AddKey(PresetInfo.STR_TARLONG).Value = presetList[i].TargetLongitude; ini.AddSection(sectionName).AddKey(PresetInfo.STR_PATHIMG1).Value = presetList[i].PathImg1; ini.AddSection(sectionName).AddKey(PresetInfo.STR_PATHIMG2).Value = presetList[i].PathImg2; } System.Console.WriteLine("=========파일 쓰기 시작==========="); ini.Save(strPath); System.Console.WriteLine("=========파일 쓰기 끝==========="); #endif } } )); }
private void SelectForm_Load(object sender, EventArgs e) { IniFile ini = new IniFile(); if (!System.IO.File.Exists("config.ini")) { MessageBox.Show("Не найден файл config.ini.\nСоздан новый."); System.IO.File.CreateText("config.ini"); } ini.Load("config.ini"); if (ini.GetSection("models") == null) { label3.Text = "Не найден раздел [models] в файле config.ini"; ini.AddSection("models"); } var models = ini.GetSection("models"); listBox1.Items.Clear(); foreach (IniFile.IniSection.IniKey k in models.Keys) { listBox1.Items.Add((string.Format(" {0}", k.Name))); } if (ini.GetSection("operations") == null) { label3.Text = "Не найден раздел [operations] в файле config.ini"; ini.AddSection("operations"); } var operations = ini.GetSection("operations"); listBox2.Items.Clear(); foreach (IniFile.IniSection.IniKey k in operations.Keys) { listBox2.Items.Add((string.Format(" {0}", k.Name))); } //Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ProjectName"); if (models.Keys.Count > 0) { listBox1.SetSelected(0, true); } if (operations.Keys.Count > 0) { listBox2.SetSelected(0, true); } var last = new IniFile(); if (!System.IO.File.Exists("last.ini")) { System.IO.File.CreateText("last.ini"); } try { last.Load("last.ini"); } catch {} if (last.GetSection("main") == null) { last.AddSection("main"); } var model = last.GetSection("main").GetKey("model"); if (model == null) { last.GetSection("main").AddKey("model"); model = last.GetSection("main").GetKey("model"); } var operation = last.GetSection("main").GetKey("operation"); if (operation == null) { last.GetSection("main").AddKey("operation"); operation = last.GetSection("main").GetKey("operation"); } if (model.Value != null) { int index = listBox1.FindStringExact(" " + model.Value); if (index != ListBox.NoMatches) { listBox1.SetSelected(index, true); } } if (operation.Value != null) { int index = listBox2.FindStringExact(" " + operation.Value); if (index != ListBox.NoMatches) { listBox2.SetSelected(index, true); } } //listBox1.SelectedItem = 3; this.KeyPreview = true; //KeyDown += new KeyEventHandler(SelectForm_KeyDown); }
/// <summary> /// Loads map information from a TS/RA2 map INI file. /// Returns true if succesful, otherwise false. /// </summary> /// <param name="path">The full path to the map INI file.</param> public bool SetInfoFromMap(string path) { if (!File.Exists(path)) { return(false); } try { IniFile iniFile = new IniFile(); iniFile.FileName = path; iniFile.AddSection("Basic"); iniFile.AddSection("Map"); iniFile.AddSection("Waypoints"); iniFile.AddSection("Preview"); iniFile.AddSection("PreviewPack"); iniFile.AddSection("ForcedOptions"); iniFile.AddSection("ForcedSpawnIniOptions"); iniFile.AllowNewSections = false; iniFile.Parse(); mapIni = iniFile; var basicSection = iniFile.GetSection("Basic"); Name = basicSection.GetStringValue("Name", "Unnamed map"); Author = basicSection.GetStringValue("Author", "Unknown author"); string gameModesString = basicSection.GetStringValue("GameModes", string.Empty); if (string.IsNullOrEmpty(gameModesString)) { gameModesString = basicSection.GetStringValue("GameMode", "Default"); } GameModes = gameModesString.Split(','); if (GameModes.Length == 0) { Logger.Log("Custom map " + path + " has no game modes!"); return(false); } for (int i = 0; i < GameModes.Length; i++) { string gameMode = GameModes[i].Trim(); GameModes[i] = gameMode.Substring(0, 1).ToUpperInvariant() + gameMode.Substring(1); } MinPlayers = 0; if (basicSection.KeyExists("ClientMaxPlayer")) { MaxPlayers = basicSection.GetIntValue("ClientMaxPlayer", 0); } else { MaxPlayers = basicSection.GetIntValue("MaxPlayer", 0); } EnforceMaxPlayers = basicSection.GetBooleanValue("EnforceMaxPlayers", true); //PreviewPath = Path.GetDirectoryName(BaseFilePath) + "/" + // iniFile.GetStringValue(BaseFilePath, "PreviewImage", Path.GetFileNameWithoutExtension(BaseFilePath) + ".png"); Briefing = basicSection.GetStringValue("Briefing", string.Empty).Replace("@", Environment.NewLine); SHA1 = Utilities.CalculateSHA1ForFile(path); IsCoop = basicSection.GetBooleanValue("IsCoopMission", false); Credits = basicSection.GetIntValue("Credits", -1); UnitCount = basicSection.GetIntValue("UnitCount", -1); NeutralHouseColor = basicSection.GetIntValue("NeutralColor", -1); SpecialHouseColor = basicSection.GetIntValue("SpecialColor", -1); HumanPlayersOnly = basicSection.GetBooleanValue("HumanPlayersOnly", false); ForceRandomStartLocations = basicSection.GetBooleanValue("ForceRandomStartLocations", false); ForceNoTeams = basicSection.GetBooleanValue("ForceNoTeams", false); PreviewPath = Path.ChangeExtension(path.Substring(ProgramConstants.GamePath.Length), ".png"); MultiplayerOnly = basicSection.GetBooleanValue("ClientMultiplayerOnly", false); string bases = basicSection.GetStringValue("Bases", string.Empty); if (!string.IsNullOrEmpty(bases)) { Bases = Convert.ToInt32(Conversions.BooleanFromString(bases, false)); } if (IsCoop) { CoopInfo = new CoopMapInfo(); string[] disallowedSides = iniFile.GetStringValue("Basic", "DisallowedPlayerSides", string.Empty).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string sideIndex in disallowedSides) { CoopInfo.DisallowedPlayerSides.Add(int.Parse(sideIndex)); } string[] disallowedColors = iniFile.GetStringValue("Basic", "DisallowedPlayerColors", string.Empty).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string colorIndex in disallowedColors) { CoopInfo.DisallowedPlayerColors.Add(int.Parse(colorIndex)); } CoopInfo.SetHouseInfos(basicSection); } localSize = iniFile.GetStringValue("Map", "LocalSize", "0,0,0,0").Split(','); actualSize = iniFile.GetStringValue("Map", "Size", "0,0,0,0").Split(','); for (int i = 0; i < MAX_PLAYERS; i++) { string waypoint = mapIni.GetStringValue("Waypoints", i.ToString(), string.Empty); if (string.IsNullOrEmpty(waypoint)) { break; } waypoints.Add(waypoint); } ParseForcedOptions(iniFile, "ForcedOptions"); ParseSpawnIniOptions(iniFile, "ForcedSpawnIniOptions"); return(true); } catch { Logger.Log("Loading custom map " + path + " failed!"); return(false); } }
public void SaveConfig() { Ini = new IniFile(); string dirs=""; foreach (String dir in SourceDirs) { if(Directory.Exists(dir)) dirs += dir + "|"; } Ini.AddSection("SOURCE_DIRS").AddKey("DIRS").SetValue(dirs); dirs = ""; foreach (CloudStorage dir in CloudStorageLst) { if (Directory.Exists(dir.Path)) dirs += dir.Name + ";" + dir.Path + ";" + dir.Size + "|"; } Ini.AddSection("OUTPUT_DIRS").AddKey("DIRS").SetValue(dirs); Ini.Save(ConfigFilename); }
/// <summary> /// Loads map information from a TS/RA2 map INI file. /// Returns true if succesful, otherwise false. /// </summary> /// <param name="path">The full path to the map INI file.</param> public bool SetInfoFromMap(string path) { try { IniFile iniFile = new IniFile(); iniFile.FileName = path; iniFile.AddSection("Basic"); iniFile.AddSection("Map"); iniFile.AddSection("Waypoints"); iniFile.AddSection("Preview"); iniFile.AddSection("PreviewPack"); iniFile.AllowNewSections = false; iniFile.Parse(); mapIni = iniFile; Name = iniFile.GetStringValue("Basic", "Name", "Unnamed map"); Author = iniFile.GetStringValue("Basic", "Author", "Unknown author"); GameModes = iniFile.GetStringValue("Basic", "GameMode", "Default").Split(','); for (int i = 0; i < GameModes.Length; i++) { string gameMode = GameModes[i].Trim(); gameMode = gameMode.Substring(0, 1).ToUpperInvariant() + gameMode.Substring(1); GameModes[i] = gameMode; } MinPlayers = 0; MaxPlayers = iniFile.GetIntValue("Basic", "MaxPlayer", 0); EnforceMaxPlayers = iniFile.GetBooleanValue("Basic", "EnforceMaxPlayers", true); //PreviewPath = Path.GetDirectoryName(BaseFilePath) + "\\" + // iniFile.GetStringValue(BaseFilePath, "PreviewImage", Path.GetFileNameWithoutExtension(BaseFilePath) + ".png"); Briefing = iniFile.GetStringValue("Basic", "Briefing", string.Empty).Replace("@", Environment.NewLine); SHA1 = Utilities.CalculateSHA1ForFile(path); IsCoop = iniFile.GetBooleanValue("Basic", "IsCoopMission", false); Credits = iniFile.GetIntValue("Basic", "Credits", -1); UnitCount = iniFile.GetIntValue("Basic", "UnitCount", -1); NeutralHouseColor = iniFile.GetIntValue("Basic", "NeutralColor", -1); SpecialHouseColor = iniFile.GetIntValue("Basic", "SpecialColor", -1); PreviewPath = Path.ChangeExtension(path.Substring(ProgramConstants.GamePath.Length + 1), ".png"); string bases = iniFile.GetStringValue("Basic", "Bases", string.Empty); if (!string.IsNullOrEmpty(bases)) { Bases = Convert.ToInt32(Conversions.BooleanFromString(bases, false)); } if (IsCoop) { CoopInfo = new CoopMapInfo(); string[] disallowedSides = iniFile.GetStringValue("Basic", "DisallowedPlayerSides", string.Empty).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string sideIndex in disallowedSides) { CoopInfo.DisallowedPlayerSides.Add(Int32.Parse(sideIndex)); } string[] disallowedColors = iniFile.GetStringValue("Basic", "DisallowedPlayerColors", string.Empty).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string colorIndex in disallowedColors) { CoopInfo.DisallowedPlayerColors.Add(Int32.Parse(colorIndex)); } CoopInfo.SetHouseInfos(iniFile, "Basic"); } localSize = iniFile.GetStringValue("Map", "LocalSize", "0,0,0,0").Split(','); actualSize = iniFile.GetStringValue("Map", "Size", "0,0,0,0").Split(','); RefreshStartingLocationPositions(); //string forcedOptionsSection = iniFile.GetStringValue("Basic", "ForcedOptions", String.Empty); //if (!string.IsNullOrEmpty(forcedOptionsSection)) //{ // string[] sections = forcedOptionsSection.Split(','); // foreach (string section in sections) // ParseForcedOptions(iniFile, section); //} //string forcedSpawnIniOptionsSection = iniFile.GetStringValue("Basic", "ForcedSpawnIniOptions", String.Empty); //if (!string.IsNullOrEmpty(forcedSpawnIniOptionsSection)) //{ // string[] sections = forcedSpawnIniOptionsSection.Split(','); // foreach (string section in sections) // ParseSpawnIniOptions(iniFile, section); //} return(true); } catch { Logger.Log("Loading custom map " + path + " failed!"); return(false); } }
/// <summary> /// Writes the spawner settings file and map file for a specific mission. /// </summary> /// <param name="mission">The mission.</param> /// <param name="selectedDifficultyLevel">The difficulty level of the mission.</param> public void WriteFilesForMission(Mission mission, int selectedDifficultyLevel, Dictionary <int, bool> globalFlagInfo) { bool copyMapsToSpawnmapINI = ClientConfiguration.Instance.CopyMissionsToSpawnmapINI; Logger.Log("Writing spawner settings and map file for a singleplayer session."); File.Delete(ProgramConstants.GamePath + ProgramConstants.SPAWNER_SETTINGS); using (StreamWriter swriter = new StreamWriter(ProgramConstants.GamePath + ProgramConstants.SPAWNER_SETTINGS)) { swriter.WriteLine("; Generated by DTA Client"); swriter.WriteLine("[Settings]"); if (copyMapsToSpawnmapINI) { swriter.WriteLine("Scenario=spawnmap.ini"); } else { swriter.WriteLine("Scenario=" + mission.Scenario); } // No one wants to play on Fastest if (UserINISettings.Instance.GameSpeed == 0) { UserINISettings.Instance.GameSpeed.Value = 1; } swriter.WriteLine("GameSpeed=" + UserINISettings.Instance.GameSpeed); swriter.WriteLine("Firestorm=" + mission.RequiredAddon); swriter.WriteLine("CustomLoadScreen=" + LoadingScreenController.GetLoadScreenName(mission.Side)); swriter.WriteLine("IsSinglePlayer=Yes"); swriter.WriteLine("SidebarHack=" + ClientConfiguration.Instance.SidebarHack); swriter.WriteLine("Side=" + mission.Side); swriter.WriteLine("BuildOffAlly=" + mission.BuildOffAlly); if (UserINISettings.Instance.EnableSPAutoSave) { swriter.WriteLine("AutoSaveGame=" + ClientConfiguration.Instance.SinglePlayerAutoSaveInterval); } UserINISettings.Instance.Difficulty.Value = selectedDifficultyLevel; swriter.WriteLine("DifficultyModeHuman=" + (mission.PlayerAlwaysOnNormalDifficulty ? "1" : selectedDifficultyLevel.ToString())); swriter.WriteLine("DifficultyModeComputer=" + GetComputerDifficulty(selectedDifficultyLevel)); swriter.WriteLine(); swriter.WriteLine(); swriter.WriteLine(); } var spawnIni = new IniFile(ProgramConstants.GamePath + ProgramConstants.SPAWNER_SETTINGS); if (globalFlagInfo != null && globalFlagInfo.Count > 0) { var globalFlagsSection = new IniSection("GlobalFlags"); spawnIni.AddSection(globalFlagsSection); foreach (var kvp in globalFlagInfo) { globalFlagsSection.SetStringValue($"GlobalFlag{ kvp.Key.ToString(CultureInfo.InvariantCulture) }", kvp.Value ? "yes" : "no"); } spawnIni.WriteIniFile(); } IniFile difficultyIni = new IniFile(ProgramConstants.GamePath + DifficultyIniPaths[selectedDifficultyLevel]); if (copyMapsToSpawnmapINI) { IniFile mapIni = new IniFile(ProgramConstants.GamePath + mission.Scenario); IniFile.ConsolidateIniFiles(mapIni, difficultyIni); // Force values of EndOfGame and SkipScore as our progression tracking currently relies on them mapIni.SetBooleanValue("Basic", "EndOfGame", true); mapIni.SetBooleanValue("Basic", "SkipScore", false); mapIni.WriteIniFile(ProgramConstants.GamePath + "spawnmap.ini"); } }
private void mainForm_FormClosing(object sender, FormClosingEventArgs e) { int FormMaximizedI = 0; Size formSize = new Size(); Point formPos = new Point(); string fontSize = fontDialog1.Font.Size.ToString(); string fontName = fontDialog1.Font.Name; //Prepare and convert variables to strings for writing. formSize.Height = this.Size.Height; formSize.Width = this.Size.Width; formPos.X = this.Location.X; formPos.Y = this.Location.Y; IniFile fsINI = new IniFile(); Uri uri = new Uri(settingsFile); //System.IO.Path.GetDirectoryName( //System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) switch(this.WindowState) { case FormWindowState.Maximized: FormMaximizedI = 1; break; case FormWindowState.Normal: FormMaximizedI = 0; break; default: break; } //Write the variables to Settings.ini fsINI.SetKeyValue("User", "FontSize", fontSize); fsINI.SetKeyValue("User", "FontName", fontName); fsINI.SetKeyValue("Application", "FormH", formSize.Height.ToString()); fsINI.SetKeyValue("Application", "FormW", formSize.Width.ToString()); fsINI.SetKeyValue("Application", "FormX", formPos.X.ToString()); fsINI.SetKeyValue("Application", "FormY", formPos.Y.ToString()); fsINI.SetKeyValue("Application", "Maximized", FormMaximizedI.ToString()); fsINI.AddSection("User").AddKey("FileInTitle").Value = "1"; fsINI.Save(uri.LocalPath + "\\Settings.ini"); }
private void backgroundWorker_backup_DoWork(object sender, DoWorkEventArgs e) { var empty_dir = false; try { if (textBox_local.Text.Trim() == "-") { var dir = Path.GetTempPath() + "\\temp_proj_dir\\"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } try { File.WriteAllText(dir + "empty.txt", ""); } catch { } git.local_dirs = new List <string> { dir }; empty_dir = true; } var sw = new System.Diagnostics.Stopwatch(); sw.Start(); warning_files = new List <string[]>(); git.progress = (p, state) => { if (p == -100) { warning_files.Add((string[])state); } else { UpdateProgress(p, state + ""); } return(null); }; git.settings.ignor_obj = ObjToolStripMenuItem.Checked; git.settings.ignor_rst = rstToolStripMenuItem.Checked; git.settings.ignor_baktmpasv = baktmpasvToolStripMenuItem.Checked; git.settings.warnin_larg_files = largfilesToolStripMenuItem.Checked; last_backup_info = git.BackUp(); if (last_backup_info.InfoSection == null) { last_backup_info.InfoSection = last_backup_info.InfoFile.AddSection("info"); } last_backup_info.InfoSection["server"] = git.server_dir; last_backup_info.InfoSection["local"] = project.LocalPath.Replace("\r", "").Replace("\n", " ; "); last_backup_info.InfoSection["BackUpSkipPattern"] = project.BackUpSkipPattern.Replace("\r", "").Replace("\n", " ; "); last_backup_info.InfoSection["machine"] = Environment.UserName + "@" + Environment.MachineName; last_backup_info.InfoSection["user"] = textBox_user.Text;; last_backup_info.InfoSection["backup-duration"] = new TSpan((int)sw.Elapsed.TotalSeconds).ToString(true); last_backup_info.ProjectSection["name"] = project.Name; last_backup_info.ProjectSection["backup_by"] = db.user.ID; last_backup_info.ProjectSection["code"] = project.code; last_backup_info.ProjectSection["manager"] = project.Manager; last_backup_info.ProjectSection["total-time"] = project.SumTimes().ToString(false); if (project.Times.Count > 0) { last_backup_info.ProjectSection["first-date"] = Utils.DateString(project.Times[0].Start); last_backup_info.ProjectSection["last-date"] = Utils.DateString(project.LastTime.End); } last_backup_info.SaveAgain(); project.LastBackup = DateTime.Now; { var proj_name = new IniFile(); var file = git.server_dir + "\\..\\نام پروژه ها.ini"; if (File.Exists(file)) { proj_name.Load(file); } var sec = proj_name.AddSection(db.user.name.Replace(" ", "_")); sec.AddKey(project.code.Replace(" ", "_"), project.Name); if (proj_name.changed) { proj_name.Save(file); } } } catch (Exception ex) { e.Result = ex; } finally { if (empty_dir) { textBox_local.Text = "-"; } } }
static void Main(string[] args) { IniFile ini = new IniFile(); ini.AddSection("TEST_SECTION").AddKey("Key1").Value = "Value1"; ini.AddSection("TEST_SECTION").AddKey("Key2").Value = "Value2"; ini.AddSection("TEST_SECTION").AddKey("Key3").Value = "Value3"; ini.AddSection("TEST_SECTION").AddKey("Key4").Value = "Value4"; ini.AddSection("TEST_SECTION").AddKey("Key5").Value = "Value5"; ini.AddSection("TEST_SECTION").AddKey("Key6").Value = "Value6"; ini.AddSection("TEST_SECTION").AddKey("Key7").Value = "Value7"; ini.AddSection("TEST_SECTION_2").AddKey("Key1").Value = "Value1"; ini.AddSection("TEST_SECTION_2").AddKey("Key2").Value = "Value2"; ini.AddSection("TEST_SECTION_2").AddKey("Key3").Value = "Value3"; ini.AddSection("TEST_SECTION_2").AddKey("Key4").Value = "Value4"; ini.AddSection("TEST_SECTION_2").AddKey("Key5").Value = "Value5"; ini.AddSection("TEST_SECTION_2").AddKey("Key6").Value = "Value6"; ini.AddSection("TEST_SECTION_2").AddKey("Key7").Value = "Value7"; // Key Rename Test Trace.Write("Key Rename Key1 -> KeyTemp Test: "); if (ini.RenameKey("TEST_SECTION", "Key1", "KeyTemp")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Section Rename Test Trace.Write("Test section rename TEST_SECTION -> TEST_SECTION_3: "); if (ini.RenameSection("TEST_SECTION", "TEST_SECTION_3")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Check Key Rename Post Section Rename Trace.Write("Test TEST_SECTION_3 rename key KeyTemp -> Key1: "); if (ini.RenameKey("TEST_SECTION_3", "KeyTemp", "Key1")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Check Section Rename Post Section Rename Trace.Write("Test section rename TEST_SECTION_3 -> TEST_SECTION: "); if (ini.RenameSection("TEST_SECTION_3", "TEST_SECTION")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Check Key Rename Key1 -> Key2 where Key2 exists Trace.Write("Test TEST_SECTION key rename Key1 -> Key2 where Key2 exists: "); if (ini.RenameKey("TEST_SECTION", "Key2", "Key1")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Check Key Rename Trace.Write("Test TEST_SECTION key rename Key2 -> Key2Renamed: "); if (ini.RenameKey("TEST_SECTION", "Key2", "Key2Renamed")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Test rename other section Trace.Write("Test section rename TEST_SECTION_2 -> TEST_SECTION_1 : "); if (ini.RenameSection("TEST_SECTION_2", "TEST_SECTION_1")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Check remove key Trace.Write("Test TEST_SECTION_1 remove key Key1: "); if (ini.GetSection("TEST_SECTION_1").RemoveKey("Key1")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Check remove key no exist Trace.Write("Test TEST_SECTION_1 remove key Key1: "); if (ini.GetSection("TEST_SECTION_1").RemoveKey("Key1")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Check remove section Trace.Write("Test remove section TEST_SECTION_1: "); if (ini.RemoveSection("TEST_SECTION_1")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } // Check remove section no exist Trace.Write("Test remove section TEST_SECTION_1: "); if (ini.RemoveSection("TEST_SECTION_1")) { Trace.WriteLine("Pass"); } else { Trace.WriteLine("Fail"); } Trace.WriteLine(String.Format("Section Count {0}", ini.Sections.Count)); foreach (IniFile.IniSection sec in ini.Sections) { Trace.WriteLine(String.Format("Section {0} Key Count {1}", sec.Name, sec.Keys.Count)); foreach (IniFile.IniSection.IniKey key in sec.Keys) { Trace.WriteLine(String.Format("Section {0} Key={1} Value={2}", sec.Name, key.Name, key.Value)); } } //Save the INI ini.Save("C:\\temp\\test.ini"); }