WriteFile() public method

Writes INI data to a text file.
public WriteFile ( string filePath, IniParser.IniData parsedData, Encoding fileEncoding = null ) : void
filePath string /// Path to the file. ///
parsedData IniParser.IniData /// IniData to be saved as an INI file. ///
fileEncoding Encoding /// Specifies the encoding used to create the file. ///
return void
コード例 #1
0
        //constructor
        public ConfigHandler()
        {            
            FileIniDataParser Parser = new FileIniDataParser();

            string configDir = String.Format(@"{0}\config", GetLocalDir());
            string configPath = String.Format(@"{0}\config\launcherConfig.ini", GetLocalDir());

            //release 0.0.
            string defaultLauncherVersion = "0.0.3";

            if (!Directory.Exists(configDir))
            {
                Directory.CreateDirectory(configDir);
            }
            if (!File.Exists(configPath))
            {
                //here we create a new empty file
                FileStream configStream = File.Create(configPath);
                configStream.Close();

                //read the file as an INI file
                try
                {
                    IniData data = Parser.ReadFile(configPath);

                    data.Sections.AddSection("Local");
                    data.Sections.AddSection("Remote");
                    data.Sections.AddSection("Launchpad");

                    data["Local"].AddKey("launcherVersion", defaultLauncherVersion);
                    data["Local"].AddKey("gameName", "Example");
                    data["Local"].AddKey("systemTarget", "Win64");

                    data["Remote"].AddKey("FTPUsername", "anonymous");
                    data["Remote"].AddKey("FTPPassword", "anonymous");
                    data["Remote"].AddKey("FTPUrl", "ftp://example.example.com");

                    data["Launchpad"].AddKey("bOfficialUpdates", "true");

                    Parser.WriteFile(configPath, data);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }
                
            }
            else 
            {
                IniData data = Parser.ReadFile(configPath);
                data["Local"]["launcherVersion"] = defaultLauncherVersion;

                Parser.WriteFile(configPath, data);
            }
        }
コード例 #2
0
ファイル: IniWriter.cs プロジェクト: redd-tsu/Skyrim-Online
        /*
         * /// <summary>
         * /// EN: Create key with value in section
         * /// </summary>
         * /// <param name="section">Section name</param>
         * /// <param name="key">Key name</param>
         * /// <param name="value">Key value</param>
         * public void setValue(string section, string key, string value)
         * {
         *
         *  if (section != null)
         *  {
         *
         *      SectionData Section = null;
         *
         *      if (data.Sections.GetSectionData(section) != null)
         *      {
         *          // Get section from data
         *          Section = data.Sections.GetSectionData(section);
         *      }
         *      else
         *      {
         *          // Creating section
         *          data.Sections.AddSection(section);
         *          // Get section from data
         *          Section = data.Sections.GetSectionData(section);
         *      }
         *
         *      if (key != null)
         *      {
         *
         *          KeyData Key = null;
         *
         *          if (Section.Keys.GetKeyData(key) != null)
         *          {
         *              // Get key from Section
         *              Key = Section.Keys.GetKeyData(key);
         *          }
         *          else
         *          {
         *              // Adding key to Sectrion
         *              Section.Keys.AddKey(key);
         *              // Get key from Section
         *              Key = Section.Keys.GetKeyData(key);
         *          }
         *
         *          if (value != null)
         *          {
         *              // Set value to key
         *              Key.Value = value;
         *          }
         *      }
         *  }
         * }
         *
         * /// <summary>
         * /// EN: TODO
         * /// </summary>
         * /// <param name="section"></param>
         * /// <param name="sectionComment"></param>
         * /// <param name="key"></param>
         * /// <param name="keyComment"></param>
         * /// <param name="value"></param>
         * public void setValue(string section, string sectionComment, string key, string keyComment, string value)
         * {
         *
         *  if (section != null)
         *  {
         *
         *      SectionData Section = null;
         *
         *      if (data.Sections.GetSectionData(section) != null)
         *      {
         *          // Get section from data
         *          Section = data.Sections.GetSectionData(section);
         *      }
         *      else
         *      {
         *          // Creating section
         *          data.Sections.AddSection(section);
         *          // Get section from data
         *          Section = data.Sections.GetSectionData(section);
         *      }
         *
         *      if (sectionComment != null && !sectionComment.Equals(""))
         *      {
         *          Section.Comments.Add(sectionComment);
         *      }
         *
         *      if (key != null)
         *      {
         *
         *          KeyData Key = null;
         *
         *          if (Section.Keys.GetKeyData(key) != null)
         *          {
         *              // Get key from Section
         *              Key = Section.Keys.GetKeyData(key);
         *          }
         *          else
         *          {
         *              // Adding key to Sectrion
         *              Section.Keys.AddKey(key);
         *              // Get key from Section
         *              Key = Section.Keys.GetKeyData(key);
         *          }
         *
         *          if (keyComment != null && !keyComment.Equals(""))
         *          {
         *              Key.Comments.Add(keyComment);
         *          }
         *
         *          if (value != null)
         *          {
         *              // Set value to key
         *              Key.Value = value;
         *          }
         *      }
         *  }
         * }
         *
         * /// <summary>
         * /// EN: TODO
         * /// </summary>
         * /// <param name="section"></param>
         * /// <param name="key_value_grupe">Group of keys and values</param>
         * public void SetValue(string section, Dictionary<string, string> keyGroup)
         * {
         *
         *  if (section != null)
         *  {
         *      SectionData Section = null;
         *
         *      try
         *      {
         *          // Get section from data
         *          Section = data.Sections.GetSectionData(section);
         *      }
         *      catch
         *      {
         *          // Creating section
         *          data.Sections.AddSection(section);
         *          // Get section from data
         *          Section = data.Sections.GetSectionData(section);
         *      }
         *
         *      if (Section != null && keyGroup != null && keyGroup.Count > 0)
         *      {
         *
         *          KeyData Key = null;
         *
         *          foreach (KeyValuePair<string, string> pair in keyGroup)
         *          {
         *              try
         *              {
         *                  // Get key from Section
         *                  Key = Section.Keys.GetKeyData(pair.Key);
         *              }
         *              catch
         *              {
         *                  // Adding key to Sectrion
         *                  Section.Keys.AddKey(pair.Key);
         *                  // Get key from Section
         *                  Key = Section.Keys.GetKeyData(pair.Key);
         *              }
         *
         *              if (Key != null && pair.Value != null)
         *              {
         *                  // Add value to key
         *                  Key.Value = pair.Value;
         *              }
         *
         *          }
         *
         *      }
         *
         *  }
         *
         * }
         */

        /// <summary>
        ///     EN: Save ini data to file
        /// </summary>
        /// <param name="filePath">file path</param>
        /// <returns>true if file saved, false otherwise</returns>
        /// <example>Example: how to save file</example>
        /// <code>if(SaveFile()) then...</code>
        public bool SaveFile()
        {
            bool result = false;

            if (path != null && data != null)
            {
                try
                {
                    parser.WriteFile(path, data);
                    result = true;
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                    result = false;
                }
            }

            if (result)
            {
                data = null;
            }

            return(result);
        }
コード例 #3
0
ファイル: Form1.cs プロジェクト: arkanoid1/BlackDesert
        private void defaultip_Click(object sender, EventArgs e)
        {
            var parser = new FileIniDataParser();
            var data = parser.ReadFile("DefaultService.ini");
            data["KR_REAL"]["AUTH_DOMAIN"] = "auth.black.game.daum.net";
            File.Delete("DefaultService.ini");
            parser.WriteFile("DefaultService.ini", data);

            serverIP.Text = @"auth.black.game.daum.net";
            serverIP.ForeColor = Color.Green;

            data = parser.ReadFile("service.ini");
            data["KR"]["AUTHENTIC_DOMAIN"] = "blackauth.black.game.daum.net";
            File.Delete("service.ini");
            parser.WriteFile("service.ini", data);

            authip.Text = @"blackauth.black.game.daum.net";
            authip.ForeColor = Color.Green;
        }
コード例 #4
0
ファイル: Form1.cs プロジェクト: arkanoid1/BlackDesert
        private void change_Click(object sender, EventArgs e)
        {
            var parser = new FileIniDataParser();
            var data = parser.ReadFile("DefaultService.ini");
            data["KR_REAL"]["AUTH_DOMAIN"] = ip1.Text;
            File.Delete("DefaultService.ini");
            parser.WriteFile("DefaultService.ini", data);

            serverIP.Text = ip1.Text;
            serverIP.ForeColor = Color.Red;

            data = parser.ReadFile("service.ini");
            data["KR"]["AUTHENTIC_DOMAIN"] = ip2.Text;
            File.Delete("service.ini");
            parser.WriteFile("service.ini", data);

            authip.Text = ip2.Text;
            authip.ForeColor = Color.Red;
        }
コード例 #5
0
        public void AddUnresolvedDependencies(AssemblyReference parentAssembly)
        {
            var parser = new FileIniDataParser();
            var versionsFileData = new IniData();

            if (!Directory.Exists(@"cache\unresolved"))
                Directory.CreateDirectory(@"cache\unresolved");

            var file = @"cache\unresolved\" + parentAssembly.Item2 + _sectionSeparator + parentAssembly.Item1 + ".ini";
            if (File.Exists(file))
                return;

            parser.WriteFile(file, versionsFileData);
        }
コード例 #6
0
ファイル: DBSelect.cs プロジェクト: NiDragon/IllTechLibrary
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            FileIniDataParser i = new FileIniDataParser();
            i.Parser.Configuration.CommentString = "#";
            IniData data = i.ReadFile(Preferences.GetConfig());

            data["DS"][AppID] = NewDbName.Text;
            retText = NewDbName.Text;

            i.WriteFile(Preferences.GetConfig(), data);

            DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }
コード例 #7
0
        public void Save(SemanticVersion version, string name, DllReference parentAssembly)
        {
            var parser = new FileIniDataParser();
            var versionsFileData = new IniData();

            versionsFileData.Sections.AddSection("Dependency");
            versionsFileData.Sections["Dependency"].AddKey("version", version.ToString());
            versionsFileData.Sections["Dependency"].AddKey("name", name);
            
            if(!Directory.Exists("cache"))
                Directory.CreateDirectory("cache");

            parser.WriteFile(@"cache\" + parentAssembly.Id.Item1 + _sectionSeparator + parentAssembly.Id.Item2 + _sectionSeparator + name + ".ini", versionsFileData);
        }
コード例 #8
0
ファイル: Form1.cs プロジェクト: Accky/FileEliminator
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            var parser = new IniParser.FileIniDataParser();
            var data   = parser.ReadFile(settingFileName);

            //書き込み
            data["Settings"]["Path"] = parameter.Path;
            string rules = "";

            foreach (var str in parameter.Rules)
            {
                rules += str + ",";
            }
            data["Settings"]["Rules"] = rules;

            parser.WriteFile(settingFileName, data);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: rickyah/ini-parser
        public static void Main()
        {
            //Create an instance of a ini file parser
            FileIniDataParser fileIniData = new FileIniDataParser();

            if (File.Exists("NewTestIniFile.ini"))
                File.Delete("NewTestIniFile.ini");

            // This is a special ini file where we use the '#' character for comment lines
            // instead of ';' so we need to change the configuration of the parser:
            fileIniData.Parser.Configuration.CommentString = "#";

            //Parse the ini file
            IniData parsedData = fileIniData.ReadFile("TestIniFile.ini");

            //Write down the contents of the ini file to the console
            Console.WriteLine("---- Printing contents of the INI file ----\n");
            Console.WriteLine(parsedData);
            Console.WriteLine();

            //Get concrete data from the ini file
            Console.WriteLine("---- Printing setMaxErrors value from GeneralConfiguration section ----");
            Console.WriteLine("setMaxErrors = " + parsedData["GeneralConfiguration"]["setMaxErrors"]);
            Console.WriteLine();

            //Modify the INI contents and save
            Console.WriteLine();

            // Modify the loaded ini file
            IniData modifiedParsedData = ModifyINIData(parsedData);

            //Write down the contents of the modified ini file to the console
            Console.WriteLine("---- Printing contents of the new INI file ----");
            Console.WriteLine(modifiedParsedData);
            Console.WriteLine();

            //Save to a file
            Console.WriteLine("---- Saving the new ini file to the file NewTestIniFile.ini ----");
            Console.WriteLine();

            // Uncomment this to change the new line string used to write the ini file to disk to
            // force use the windows style new line
            //modifiedParsedData.Configuration.NewLineStr = "\r\n";
            fileIniData.WriteFile("NewTestIniFile.ini", modifiedParsedData);
        }
コード例 #10
0
 public static void Locate()
 {
     FileIniDataParser parser = new FileIniDataParser();
     IniData data = parser.ReadFile("config.ini");
     for (int i = 1; i <= 17; i++)
     {
         if (MessageBox.Show("Please set the cursor on your collector number " + i + " and press enter. Click on cancel if not available", "Collectors localization", MessageBoxButtons.OKCancel) == DialogResult.OK)
         {
             Point collectorPos = FindCursorPos();
             data["collectors"]["collector" + i] = collectorPos.X + ";" + collectorPos.Y;
             Home.bsProcess.mouse.SendClick(WButton.Left, collectorPos, false);
         }
         else
             data["collectors"]["collector" + i] = "-1;-1";
     }
     parser.WriteFile("config.ini", data);
     Home.bsProcess.mouse.SendClick(WButton.Left, new Point(0,0), false);
 }
コード例 #11
0
        private bool WriteBookToINI()
        {
            var     parser = new IniParser.FileIniDataParser();
            IniData 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);
        }
コード例 #12
0
        public static void SetPrefs(String Key, String Value)
        {
            FileIniDataParser i = new FileIniDataParser();
            i.Parser.Configuration.CommentString = "#";
            IniData data = i.ReadFile(GetConfig());

            data["PREFS"][Key] = Value;

            i.WriteFile(GetConfig(), data);
        }
コード例 #13
0
        public static void SetPosition(String AppID, Point point)
        {
            if (point.X < 0 || point.Y < 0)
                return;

            FileIniDataParser i = new FileIniDataParser();
            i.Parser.Configuration.CommentString = "#";
            IniData data = i.ReadFile(GetConfig());

            String key = String.Format("{0}_Pos", AppID);

            // If our key does not exist we must add it!
            if (data["PREFS"].GetKeyData(key) == null)
            {
                data["PREFS"].AddKey(key);
            }

            data["PREFS"][key] = String.Format("{0}, {1}", point.X, point.Y);

            i.WriteFile(GetConfig(), data);
        }
コード例 #14
0
        public static void SetMax(String AppID, FormWindowState State)
        {
            FileIniDataParser i = new FileIniDataParser();

            i.Parser.Configuration.CommentString = "#";

            IniData data = i.ReadFile(GetConfig());

            String key = String.Format("{0}_Maxed", AppID);

            // If our key does not exist we must add it!
            if (data["PREFS"].GetKeyData(key) == null)
            {
                data["PREFS"].AddKey(key);
            }

            data["PREFS"][key] = Convert.ToString(State == FormWindowState.Maximized);

            i.WriteFile(GetConfig(), data);
        }
コード例 #15
0
ファイル: Home.cs プロジェクト: Jeremymav/ClashofBots
 private void flatComboBox_attackMode_SelectedIndexChanged_1(object sender, EventArgs e)
 {
     FileIniDataParser parser = new FileIniDataParser();
     IniData data = parser.ReadFile("config.ini");
     data["attack"]["mode"] = flatComboBox_attackMode.SelectedIndex.ToString();
     parser.WriteFile("config.ini", data);
 }
コード例 #16
0
ファイル: Home.cs プロジェクト: Jeremymav/ClashofBots
 private void flatComboBox_barrack4_SelectedIndexChanged(object sender, EventArgs e)
 {
     FileIniDataParser parser = new FileIniDataParser();
     IniData data = parser.ReadFile("config.ini");
     data["troops"]["barrack4"] = flatComboBox_barrack4.SelectedIndex.ToString();
     parser.WriteFile("config.ini", data);
 }
コード例 #17
0
ファイル: ConfigurationManager.cs プロジェクト: Onkeliroh/DSA
 /// <summary>
 /// Saves the general settings.
 /// </summary>
 public void SaveGeneralSettings()
 {
     if (UserFolder != null) {
         var Parser = new FileIniDataParser ();
         Parser.WriteFile (UserFolder, GeneralData, System.Text.Encoding.UTF8);
     }
 }
コード例 #18
0
ファイル: Home.cs プロジェクト: Jeremymav/ClashofBots
 private void flatCheckBox_trophy_CheckedChanged(object sender)
 {
     FileIniDataParser parser = new FileIniDataParser();
     IniData data = parser.ReadFile("config.ini");
     data["search"]["btrophy"] = flatCheckBox_trophy.Checked.ToString();
     parser.WriteFile("config.ini", data);
 }
コード例 #19
0
 public void Save(string path) {
   if (Config == null) { return; }
   var parser = new FileIniDataParser();
   parser.WriteFile(path, Config);
 }
コード例 #20
0
ファイル: Home.cs プロジェクト: Jeremymav/ClashofBots
 private void flatNumeric_deployTime_ValueChange(object sender, EventArgs e)
 {
     FileIniDataParser parser = new FileIniDataParser();
     IniData data = parser.ReadFile("config.ini");
     data["attack"]["deploytime"] = flatNumeric_deployTime.Value.ToString();
     parser.WriteFile("config.ini", data);
 }
コード例 #21
0
ファイル: Info.cs プロジェクト: Pdraw/Pdraw-old-
 /// <summary>
 /// 
 /// </summary>
 public static void SaveSetting()
 {
     var parser = new FileIniDataParser();
     parser.WriteFile("../../Setting.ini", SettingData, Encoding.UTF8);
 }
コード例 #22
0
ファイル: frmMain.cs プロジェクト: marcomanieri/IFME
		void LangCreate()
		{
			var parser = new FileIniDataParser();
			IniData data = new IniData();

			data.Sections.AddSection("info");
			data.Sections["info"].AddKey("Code", "en"); // file id
			data.Sections["info"].AddKey("Name", "English");
			data.Sections["info"].AddKey("Author", "Anime4000");
			data.Sections["info"].AddKey("Version", $"{Global.App.VersionRelease}");
			data.Sections["info"].AddKey("Contact", "https://github.com/Anime4000");
			data.Sections["info"].AddKey("Comment", "Please refer IETF Language Tag here: http://www.i18nguy.com/unicode/language-identifiers.html");

			data.Sections.AddSection(Name);
			Control ctrl = this;
			do
			{
				ctrl = GetNextControl(ctrl, true);

				if (ctrl != null)
					if (ctrl is Label ||
						ctrl is Button ||
						ctrl is TabPage ||
						ctrl is CheckBox ||
						ctrl is RadioButton ||
						ctrl is GroupBox)
						if (!string.IsNullOrEmpty(ctrl.Text))
							data.Sections[Name].AddKey(ctrl.Name, ctrl.Text.Replace("\n", "\\n").Replace("\r", ""));

			} while (ctrl != null);

			foreach (ToolStripItem item in cmsQueueMenu.Items)
				if (item is ToolStripMenuItem)
					data.Sections[Name].AddKey(item.Name, item.Text);

			foreach (ToolStripItem item in tsmiQueueAviSynth.DropDownItems)
				if (item is ToolStripMenuItem)
					data.Sections[Name].AddKey(item.Name, item.Text);

			foreach (ColumnHeader item in lstQueue.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			foreach (ColumnHeader item in lstSub.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			foreach (ColumnHeader item in lstAttach.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			data.Sections.AddSection(Name);
			data.Sections[Name].AddKey("BenchmarkDownload", Language.BenchmarkDownload);
			data.Sections[Name].AddKey("BenchmarkNoFile", Language.BenchmarkNoFile);
			data.Sections[Name].AddKey("NotSupported", Language.NotSupported);
			data.Sections[Name].AddKey("OneItem", Language.OneItem);
			data.Sections[Name].AddKey("OneVideo", Language.OneVideo);
			data.Sections[Name].AddKey("SaveNewProfilesInfo", Language.SaveNewProfilesInfo);
			data.Sections[Name].AddKey("SaveNewProfilesTitle", Language.SaveNewProfilesTitle);
			data.Sections[Name].AddKey("SelectAviSynth", Language.SelectAviSynth);
			data.Sections[Name].AddKey("SelectNotAviSynth", Language.SelectNotAviSynth);
			data.Sections[Name].AddKey("SelectOneVideoAttch", Language.SelectOneVideoAttch);
			data.Sections[Name].AddKey("SelectOneVideoPreview", Language.SelectOneVideoPreview);
			data.Sections[Name].AddKey("SelectOneVideoSubtitle", Language.SelectOneVideoSubtitle);
			data.Sections[Name].AddKey("VideoToAviSynth", Language.VideoToAviSynth.Replace("\n", "\\n"));
			data.Sections[Name].AddKey("QueueSave", Language.QueueSave);
			data.Sections[Name].AddKey("QueueSaveError", Language.QueueSaveError);
			data.Sections[Name].AddKey("QueueOpenChange", Language.QueueOpenChange);
			data.Sections[Name].AddKey("Quit", Language.Quit);

			data.Sections[Name].AddKey("TipUpdateTitle", Language.TipUpdateTitle);
			data.Sections[Name].AddKey("TipUpdateMessage", Language.TipUpdateMessage);

			for (int i = 0; i < cboPictureYadifMode.Items.Count; i++)
				data.Sections[Name].AddKey($"DeInterlaceMode{i}", (string)cboPictureYadifMode.Items[i]);

			for (int i = 0; i < cboPictureYadifField.Items.Count; i++)
				data.Sections[Name].AddKey($"DeInterlaceField{i}", (string)cboPictureYadifField.Items[i]);

			for (int i = 0; i < cboPictureYadifFlag.Items.Count; i++)
				data.Sections[Name].AddKey($"DeInterlaceFlag{i}", (string)cboPictureYadifFlag.Items[i]);

			data.Sections[Name].AddKey("Untitled", Language.Untitled);
			data.Sections[Name].AddKey("Untitled", Language.Donate);

			parser.WriteFile(Path.Combine(Global.Folder.Language, "en.ini"), data, Encoding.UTF8);		
		}
コード例 #23
0
ファイル: Home.cs プロジェクト: Jeremymav/ClashofBots
 private void flatTextBox_trophy_TextChanged(object sender, EventArgs e)
 {
     FileIniDataParser parser = new FileIniDataParser();
     IniData data = parser.ReadFile("config.ini");
     data["search"]["trophy"] = flatTextBox_trophy.Text;
     parser.WriteFile("config.ini", data);
 }
コード例 #24
0
        public static void SetSize(String AppID, Form wnd)
        {
            if (GetMax(AppID) == FormWindowState.Maximized)
                return;

            FileIniDataParser i = new FileIniDataParser();

            i.Parser.Configuration.CommentString = "#";

            IniData data = i.ReadFile(GetConfig());

            String key = String.Format("{0}_Size", AppID);

            // If our key does not exist we must add it!
            if (data["PREFS"].GetKeyData(key) == null)
            {
                data["PREFS"].AddKey(key);
            }

            data["PREFS"][key] = String.Format("{0}, {1}", wnd.Size.Width, wnd.Size.Height);

            i.WriteFile(GetConfig(), data);
        }
コード例 #25
0
ファイル: MySQLSet.cs プロジェクト: NiDragon/IllTechLibrary
        private bool SaveInfo()
        {
            String password = "";

            if (UPassText.Text == String.Empty ||
                UNameText.Text == String.Empty ||
                UIPText.Text == String.Empty ||
                UPortText.Text == String.Empty)
                return false;

            if (EncryptPwdCheck.Checked)
            {
                StringBuilder sb = new StringBuilder(UPassText.Text);

            #if !MONO
                if (Encrypt_Password(sb, 0x49434C30))
            #else
                if(Encrypt_Password(UPassText.Text, out password, 0x49434C30))
            #endif
                {
            #if !MONO
                    password = BitConverter.ToString(Encoding.ASCII.GetBytes(sb.ToString())).Replace("-", "");
            #endif
                }
                else
                {
                    return false;
                }
            }
            else
            {
                password = UPassText.Text;
            }

            //Create an instance of a ini file parser
            FileIniDataParser fileIniData = new FileIniDataParser();

            if (!File.Exists(Preferences.GetConfig()))
            {
                return false;
            }

            fileIniData.Parser.Configuration.CommentString = "#";

            //Parse the ini file
            IniData parsedData = fileIniData.ReadFile(Preferences.GetConfig());

            parsedData["HOST"]["IP"] = UIPText.Text;
            parsedData["HOST"]["Port"] = UPortText.Text;

            parsedData["HOST"]["User"] = UNameText.Text;
            parsedData["HOST"]["Pass"] = password;
            parsedData["HOST"]["Encrypt"] = Convert.ToString(EncryptPwdCheck.Checked);

            fileIniData.WriteFile(Preferences.GetConfig(), parsedData);

            return true;
        }
コード例 #26
0
 public void SaveSettings(string fileName)
 {
     if (ParsedConfig == null)
         ParsedConfig = new IniData();
     // Note that this will persist the merged global & user configurations, not the original global config.
     // Since we don't call this method from production code, this is not an issue.
     // TODO: parserConfig is also created in ParseFiles. Consider making it a static member for consistency.
     var parserConfig = new IniParserConfiguration {
         // ThrowExceptionsOnError = false,
         CommentString = "#",
         SkipInvalidLines = true
     };
     var parser = new IniDataParser(parserConfig);
     var fileParser = new FileIniDataParser(parser);
     var utf8 = new UTF8Encoding(false);
     fileParser.WriteFile(fileName, ParsedConfig, utf8);
 }
コード例 #27
0
ファイル: URLHandlers.cs プロジェクト: Wetmelon/CKAN
        private static void RegisterURLHandler_Linux()
        {
            var parser = new FileIniDataParser();
            IniData data;

            log.InfoFormat("Trying to register URL handler");

            if (!File.Exists(MimeAppsListPath))
            {
                log.InfoFormat("{0} does not exist, trying to create it", MimeAppsListPath);
                File.WriteAllLines(MimeAppsListPath, new string[] { "[Default Applications]" });
            }

            try
            {
                data = parser.ReadFile(MimeAppsListPath);
            }
            catch (DirectoryNotFoundException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }
            catch (FileNotFoundException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }
            catch (ParsingException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }

            if (data["Added Associations"] == null)
            {
                data.Sections.AddSection("Added Associations");
            }
            data["Added Associations"].RemoveKey("x-scheme-handler/ckan");
            data["Added Associations"].AddKey("x-scheme-handler/ckan", HandlerFileName);

            parser.WriteFile(MimeAppsListPath, data);

            var handlerPath = Path.Combine(ApplicationsPath, HandlerFileName);
            var handlerDirectory = Path.GetDirectoryName(handlerPath);

            if (handlerDirectory == null || !Directory.Exists(handlerDirectory))
            {
                log.ErrorFormat("Error: {0} doesn't exist", handlerDirectory);
                return;
            }

            if (File.Exists(handlerPath))
            {
                File.Delete(handlerPath);
            }

            File.WriteAllText(handlerPath, "");
            data = parser.ReadFile(handlerPath);
            data.Sections.AddSection("Desktop Entry");
            data["Desktop Entry"].AddKey("Version", "1.0");
            data["Desktop Entry"].AddKey("Type", "Application");
            data["Desktop Entry"].AddKey("Exec", "mono " + System.Reflection.Assembly.GetExecutingAssembly().Location + " gui %u");
            data["Desktop Entry"].AddKey("Icon", "ckan");
            data["Desktop Entry"].AddKey("StartupNotify", "true");
            data["Desktop Entry"].AddKey("Terminal", "false");
            data["Desktop Entry"].AddKey("Categories", "Utility");
            data["Desktop Entry"].AddKey("MimeType", "x-scheme-handler/ckan");
            data["Desktop Entry"].AddKey("Name", "CKAN Launcher");
            data["Desktop Entry"].AddKey("Comment", "Launch CKAN");

            parser.WriteFile(handlerPath, data);
            AutoUpdate.SetExecutable(handlerPath);
        }
コード例 #28
0
        public static void CreateDefault()
        {
            //Create ini file
            FileIniDataParser parser = new FileIniDataParser();
            IniData data = new IniData();

            //Add global section
            data.Sections.AddSection("game");

            //Add global settings
            data["game"]["hidemode"] = "1";

            //Add collectors section
            data.Sections.AddSection("collectors");

            //Add collectors locations
            for (int i = 1; i <= 17; i++)
            {
                data["collectors"]["collector" + i] = "-1:-1";
            }

            //Add troops section
            data.Sections.AddSection("troops");

            //Add troops settings
            for (int i = 1; i <= 4; i++)
            {
                data["troops"]["barrack" + i] = "0";
            }

            //Add search section
            data.Sections.AddSection("search");

            //Add search settings
            data["search"]["gold"] = "50000";
            data["search"]["elixir"] = "50000";
            data["search"]["dark"] = "0";
            data["search"]["trophy"] = "0";
            data["search"]["bgold"] = "1";
            data["search"]["belixir"] = "1";
            data["search"]["bdark"] = "0";
            data["search"]["btrophy"] = "0";
            data["search"]["alert"] = "0";

            //Add attack section
            data.Sections.AddSection("attack");

            //Add attack settings
            data["attack"]["topleft"] = "True";
            data["attack"]["topright"] = "True";
            data["attack"]["bottomleft"] = "True";
            data["attack"]["bottomright"] = "True";
            data["attack"]["mode"] = "0";
            data["attack"]["maxtrophy"] = "1000";
            data["attack"]["bmaxtrophy"] = "False";
            data["attack"]["deploytime"] = "75";

            //Save the file
            parser.WriteFile(AppSettings.Cfg.FilePath, data);
        }
コード例 #29
0
        private static void Save(string privilege, HashSet<string> grants)
        {
            string inFile = Path.GetTempFileName();

            try
            {
                var updatedConfiguration = new IniData();
                updatedConfiguration.Sections.AddSection("Unicode");
                updatedConfiguration.Sections.AddSection("Version");
                updatedConfiguration.Sections.AddSection(PrivilegeRightsSection);

                updatedConfiguration["Unicode"]["Unicode"] = "yes";
                updatedConfiguration["Version"]["signature"] = "\"$CHICAGO$\"";
                updatedConfiguration["Version"]["revision"] = "1";

                string grantsValue = string.Join(",", grants.ToArray());

                updatedConfiguration[PrivilegeRightsSection][privilege] = grantsValue;

                FileIniDataParser iniFile = new FileIniDataParser();
                iniFile.WriteFile(inFile, updatedConfiguration);

                string command = string.Format(
                    CultureInfo.InvariantCulture,
                    "secedit.exe /configure /db secedit.sdb /cfg \"{0}\"",
                    inFile);

                int exitCode = Utilities.Command.ExecuteCommand(command);

                if (exitCode != 0)
                {
                    throw new PrisonException("secedit exited with code {0} while trying to to save privileges", exitCode);
                }
            }
            finally
            {
                File.Delete(inFile);
            }
        }
コード例 #30
0
ファイル: frmMain.cs プロジェクト: marcomanieri/IFME
		private void btnProfileSave_Click(object sender, EventArgs e)
		{
			if (cboProfile.SelectedIndex == -1) // Error free
				return;

			var i = cboProfile.SelectedIndex;
			var p = Profile.List[i == 0 ? 0 : i - 1];

			string file;
			string platform;
			string name;
			string author;
			string web;

			if (i == 0)
			{
				file = Path.Combine(Global.Folder.Profile, $"{DateTime.Now:yyyyMMdd_HHmmss}.ifp");
				platform = "User";
				name = $"{DateTime.Now:yyyy-MM-dd_HH:mm:ss}";
				author = Environment.UserName;
				web = "";
			}
			else
			{
				file = p.File;
				platform = p.Info.Platform;
				name = p.Info.Name;
				author = p.Info.Author;
				web = p.Info.Web;
			}

			using (var form = new frmInputBox(Language.SaveNewProfilesTitle, Language.SaveNewProfilesInfo, name))
			{
				var result = form.ShowDialog();
				if (result == DialogResult.OK)
				{
					name = form.ReturnValue; // return
				}
				else
				{
					return;
				}
			}

			var parser = new FileIniDataParser();
			IniData data = new IniData();

			data.Sections.AddSection("info");
			data["info"].AddKey("format", rdoMKV.Checked ? "mkv" : "mp4");
			data["info"].AddKey("platform", platform);
			data["info"].AddKey("name", name);
			data["info"].AddKey("author", author);
			data["info"].AddKey("web", web);

			data.Sections.AddSection("picture");
			data["picture"].AddKey("resolution", cboPictureRes.Text);
			data["picture"].AddKey("framerate", cboPictureFps.Text);
			data["picture"].AddKey("bitdepth", cboPictureBit.Text);
			data["picture"].AddKey("chroma", cboPictureYuv.Text);

			data.Sections.AddSection("video");
			data["video"].AddKey("preset", cboVideoPreset.Text);
			data["video"].AddKey("tune", cboVideoTune.Text);
			data["video"].AddKey("type", cboVideoType.SelectedIndex.ToString());
			data["video"].AddKey("value", txtVideoValue.Text);
			data["video"].AddKey("cmd", txtVideoCmd.Text);

			data.Sections.AddSection("audio");
			data["audio"].AddKey("encoder", $"{cboAudioEncoder.SelectedValue}");
			data["audio"].AddKey("bitrate", cboAudioBit.Text);
			data["audio"].AddKey("frequency", cboAudioFreq.Text);
			data["audio"].AddKey("channel", cboAudioChannel.Text);
			data["audio"].AddKey("compile", chkAudioMerge.Checked ? "true" : "false");
			data["audio"].AddKey("cmd", txtAudioCmd.Text);

			parser.WriteFile(file, data, Encoding.UTF8);
			Profile.Load(); //reload list
			ProfileAdd();
		}
コード例 #31
0
ファイル: StartupWizard.cs プロジェクト: decred/Paymetheus
        private async void Connect()
        {
            try
            {
                ConnectCommand.Executable = false;

                if (string.IsNullOrWhiteSpace(ConsensusServerNetworkAddress))
                {
                    MessageBox.Show("Network address is required");
                    return;
                }
                if (string.IsNullOrWhiteSpace(ConsensusServerRpcUsername))
                {
                    MessageBox.Show("RPC username is required");
                    return;
                }
                if (ConsensusServerRpcPassword.Length == 0)
                {
                    MessageBox.Show("RPC password may not be empty");
                    return;
                }
                if (!File.Exists(ConsensusServerCertificateFile))
                {
                    MessageBox.Show("Certificate file not found");
                    return;
                }

                var rpcOptions = new ConsensusServerRpcOptions(ConsensusServerNetworkAddress,
                    ConsensusServerRpcUsername, ConsensusServerRpcPassword, ConsensusServerCertificateFile);
                try
                {
                    await App.Current.Synchronizer.WalletRpcClient.StartConsensusRpc(rpcOptions);
                }
                catch (RpcException ex) when (ex.Status.StatusCode == StatusCode.NotFound)
                {
                    var msg = string.Format("Unable to connect to {0}.\n\nConnection could not be established with `{1}`.",
                        ConsensusServerRpcOptions.ApplicationName, ConsensusServerNetworkAddress);
                    MessageBox.Show(msg, "Error");
                    return;
                }
                catch (Exception ex) when (ErrorHandling.IsTransient(ex) || ErrorHandling.IsClientError(ex))
                {
                    MessageBox.Show($"Unable to connect to {ConsensusServerRpcOptions.ApplicationName}.\n\nCheck authentication settings and try again.", "Error");
                    return;
                }

                await Task.Run(() =>
                {
                    // save defaults to a file so that the user doesn't have to type this information again
                    var ini = new IniData();
                    ini.Sections.AddSection("Application Options");
                    ini["Application Options"]["rpcuser"] = ConsensusServerRpcUsername;
                    ini["Application Options"]["rpcpass"] = ConsensusServerRpcPassword;
                    ini["Application Options"]["rpclisten"] = ConsensusServerNetworkAddress;
                    ini["Application Options"]["rpccert"] = ConsensusServerCertificateFile;
                    var appDataDir = Portability.LocalAppData(Environment.OSVersion.Platform,
                                        AssemblyResources.Organization, AssemblyResources.ProductName);
                    var parser = new FileIniDataParser();
                    parser.WriteFile(Path.Combine(appDataDir, "defaults.ini"), ini);
                });

                var walletExists = await App.Current.Synchronizer.WalletRpcClient.WalletExistsAsync();
                if (!walletExists)
                {
                    _wizard.CurrentDialog = new PickCreateOrImportSeedDialog(Wizard);
                }
                else
                {
                    // TODO: Determine whether the public encryption is enabled and a prompt for the
                    // public passphrase prompt is needed before the wallet can be opened.  If it
                    // does not, then the wallet can be opened directly here instead of creating
                    // another dialog.
                    _wizard.CurrentDialog = new PromptPublicPassphraseDialog(Wizard);

                    //await _walletClient.OpenWallet("public");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                ConnectCommand.Executable = true;
            }
        }
コード例 #32
0
ファイル: frmOption.cs プロジェクト: zeruel11/IFME
		void LangCreate()
		{
			var parser = new FileIniDataParser();
			IniData data = parser.ReadFile(Path.Combine(Global.Folder.Language, "en.ini"));

			data.Sections[Name].AddKey("title", Text);

			data.Sections.AddSection(Name);
			Control ctrl = this;
			do
			{
				ctrl = GetNextControl(ctrl, true);

				if (ctrl != null)
					if (ctrl is Label ||
						ctrl is Button ||
						ctrl is TabPage ||
						ctrl is CheckBox ||
						ctrl is RadioButton ||
						ctrl is GroupBox)
						if (!string.IsNullOrEmpty(ctrl.Text))
							data.Sections[Name].AddKey(ctrl.Name, ctrl.Text.Replace("\n", "\\n").Replace("\r", ""));

			} while (ctrl != null);

			data.Sections[Name].AddKey($"VisitWeb", "Visit &Website");

			foreach (ColumnHeader item in lstPlugin.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			foreach (ColumnHeader item in lstExtension.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			foreach (ColumnHeader item in lstProfile.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			data.Sections[Name].AddKey("Installed", Language.Installed);
			data.Sections[Name].AddKey("NotInstalled", Language.NotInstalled);

			parser.WriteFile(Path.Combine(Global.Folder.Language, "en.ini"), data);
		}
コード例 #33
-1
ファイル: ConfigHandler.cs プロジェクト: furesoft/Launchpad
		/// <summary>
		/// Writes the config data to disk. This method is thread-blocking, and all write operations 
		/// are synchronized via lock(WriteLock).
		/// </summary>
		/// <param name="Parser">The parser dealing with the current data.</param>
		/// <param name="Data">The data which should be written to file.</param>
		private void WriteConfig(FileIniDataParser Parser, IniData Data)
		{
			lock (WriteLock)
			{
				Parser.WriteFile (GetConfigPath (), Data);
			}
		}