Given an app.config file, How can I read the keys and values given that those keys I am interested in will all follow a pattern I establish first. For example I do know that all the names of my keys will follow a pattern of
<add key="my_*_Def" value = "someValue">
The thing is I want to write a program that I can give these config files to it and then my program goes and finds that pattern in that file and gives them to me for further processing.
Is there a better way for writing this other than treating it as a text file and reading it line by line?
You can use
ConfigurationManager.AppSettings.AllKeys
to find all the keys in the app.config file. (link)
To try in another file, you'll want to get the configuration using ConfigurationManager.OpenExeConfiguration Method (String)
So;
var config = ConfigrationManager.OpenExeConfiguration("foo.exe.config");
var keys = config.AppSettings.AllKeys;
Related
I have the following code to change key value in Web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
webConfigApp.AppSettings.Settings["Email"].Value = "abc#def.com";
webConfigApp.Save();
It changes the value successfully but it also affects the file structure. I have some comments in the file that comments are gone after running the above code.
Is there any code which only updates the key value and not affects the entire file?
There is an overload on Save method that is
Save(ConfigurationSaveMode)
If you set it to Minimal it will save only the changed properties.
Please take a look at https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationsavemode?view=netframework-4.8
I have a list box and that list box contain multiple string value. I want to add those strings to config file and want to read values from config and put it in list box. what should be the approach? I am new to configuration file.
The following snippet will help you modify the app.config file of your project.
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Remove("MySetting");
config.AppSettings.Settings.Add("MySetting", "some value");
config.Save(ConfigurationSaveMode.Modified);
For reading the config values, you can simply use ConfigurationManager.AppSettings["MySetting"]
You can store and retrieve configuration data for your app via it's app.config file.
You'll need to add a reference to System.Configuration in your code and add the System.Configuration assembly to your application.
Here is a good post with more info - What is App.config in C#.NET? How to use it?
probably you wanted to have those values present in a file and then read from that file and attach to your listbox like
string path = #"c:\temp\MyTest.txt";
if (File.Exists(path))
{
string[] readText = File.ReadAllLines(path);
}
You can attach that your listbox
listbox1.DataSource = new List<string>().AddRange(readText);
I'm trying to convert my C++ code to Visual C#. My goal is to be able to read a INI file (not a XML file !) with some sections. Each line is assigned to a button and each button launch a command. Each INI line has 4 value, separated by a ";".
For example :
[Button_section1]
Button1=Button Scenario;open;notepad;/a;scenario.txt
Means :
List item
Button1 : real name of the button
Button Scenario : the text (dipslayed name) of the button
open : initial command (can be print or explore too...
notepad : executable (can be any file or CMD for another example)
/a : first argument
scenario.txt : 2nd argument
So, in my previous code, I had 25 methods ReadSection and StringSepare, which was able to read each section of my INI file then put in array with the StringSepare method
When loading the form, the Button Text can be displayed from the INI file with following
Button bt = (Button)this.Controls.Find(i, true)[0];
Then clicking on the button allow to launch the following command :
(open in this case) -> notepad /a scenario.txt
NOTES :
I don't want to use any XML file, because I have a link with my SQL BD, which is interpretated as a CSV file. In fact, it is a CSV file with sections.,..
I also want to plug my own ini-parser library
https://github.com/rickyah/ini-parser
You can install it with NuGet, supports Mono and it's MIT licensed, also its really easy to use
// Load INI file from path, Stream or TextReader.
var p = new FileIniDataParser();
// ; is also the default comment string, you need to change it
p.Parser.Configuration.CommentString = "//";
// Load the file
IniData parsedData = parser.LoadFile("TestIniFile.ini");
// your information
var buttonData = parsedData["Button_section1"]["Button1"].Split(new {}[";"])
You can access the sections and keys in the sections directly if you want to gather the data about each button:
foreach(SectionData section in parsedData.Sections)
foreach(KeyData key in section.Keys)
Hope it is useful to you, and I accept PRs if you have any improvement ;)
Hi Benji you can use my library to help you process your INI files:
https://github.com/MarioZ/MadMilkman.Ini
For example:
// Set INI file's format options.
IniOptions option = new IniOptions();
// By default "CommentStarter" is ';' but you are using it as a
// multiple values separator so you need to change "CommentStarter"
option.CommentStarter = IniCommentStarter.Hash;
// Load INI file from path, Stream or TextReader.
IniFile ini = new IniFile(option);
ini.Load("Sample.ini");
// Select file's section.
IniSection sec = ini.Sections["Button_section1"];
// Select section's key.
IniKey key = sec.Keys["Button1"];
// Get key's values.
string[] values = key.Value.Split(';');
Also as an FYI, the library has a support for parsing multiple values (int-s, string-s, bool-s, etc.) but the syntax is different, it recognises the following:
Button1={Button Scenario,open,notepad,/a,scenario.txt}
With an above syntax you could do the following:
// Get key's values.
string[] values;
key.TryParseValue(out values);
Nevertheless I hope it's helpful to you, note that you can find additional samples in a sample projects (C# and C++/CLI) on the following link:
https://github.com/MarioZ/MadMilkman.Ini/tree/master/MadMilkman.Ini.Samples
I am trying to read the app settings in the config file of another application (app.exe.config).
I have tried several things. Most recently I used this:
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(FullPath() + ".config");
// Get the AppSetins section.
AppSettingsSection appSettingSection = config.AppSettings;
// Display raw xml.
Debug.WriteLine(appSettingSection.SectionInformation.GetRawXml());
but the GetRawXml() returns nothing. Where am I going wrong? The FullPath() method returns the correct path, I have tested this.
M
Config files are valid xml files so you can also try using XElement.Load(filepath) and process the xml tree as desired.
var appSettingsRawXml = System.Xml.Linq.XElement.Load(FullPath() + ".config")
.Element("appSettings")
.ToString();
GetRawXml supports the .NET Framework infrastructure and is not intended to be used directly from your code. MSDN
I have put a config ini file "config.ini" for reading and writing to from my C# program, the thing is, if the user has UAC enabled then for some weird reasons the program doesn't read or write to the file but it managed to create the file but cannot read or write to it.
How can I get this to work.
this file is saved into DOCUMENTSFOLDER\ProductName\config.ini
Ini class file: http://www.sinvise.net/so/Ini.cs
Code Snippet of config.ini creation: http://www.sinvise.net/so/creation.txt
Quick suggestion before going further, you should check out nini which is a neat INI handler and takes care of the reading/writing the INI files.
Sample usage of the code that reads from the ini file.
using Nini;
using Nini.Config;
namespace niniDemo{
public class niniDemoClass{
public bool LoadIni(){
string configFileName = "demo.ini";
IniConfigSource configSource = new IniConfigSource(configFileName);
IConfig demoConfigSection = configSource.Configs["Demo"];
string demoVal = demoConfigSection.Get("demoVal", string.Empty);
}
}
}
Try that and take it from there...
Hope this helps,
Best regards,
Tom.
You should have better luck writing to the path: Environment.SpecialFolder.LocalApplicationData. Your app should have permission to write to that with UAC on or off, or even on machines where the app/user has very limited permissions.