I want to add/remove/upsert a line for ADO .NET data provider programmatically with C#.
My first thought was to parse the file with some parser (like Eto.Parse), then add/remove necessary span of text and then write a new file into install image directory (which is not write protected unlike to write protected main machine.config).
Then I think, that the file is xml, and it is possible to use existing xml machinery instead of custom parser. Load XML, build object model from XML, modify it and serialize.
Then I realise, that object model for working with configs is already present in System.Configuraion namespace.
And I decide to search an existing example on how to modify the machine config with these classes. I found only an example how to obtain it's location new ConfigurationFileMap().MachineConfigFilename; (see The best way to get a path to machine.config of a different .NET version)
Just tell the ConfigManager that you are looking to edit something other than the current app's config file.
Configuration config = ConfigurationManager.OpenMachineConfiguration();
The, you can use config.sections[whatever] to access specific sections.
Keep in mind that the config object maps out most of the properties you are attempting to tweak, so you'll need to dig through the specific section's interface to find exactly what you're trying to mess-up update.
Related
I know the easiest way to generate a config file is through visual studio. however the environment my program is going to be functioning in we are going to have several different configurations and the application needs to be able to build the config files on its own. Just curious if there is an easier way than making a large string literal and then copying over to a new file. Thanks for any help.
Not sure what kind of information you want to save in generated configurations.
If you are using only appSettings section which as only key values, then it would be better to generate a JSON file. It is very easy to generate it using newtonsoft.json.
in your app.config file you can keep the path of JSON file and load the settings at app startup if the file is already available.
NOTE:
JSON can also store any kind of complex configurations, you will have to generate the classes to hold those configurations.
Once you application puts value in these objects, serialize it to JSON and keep it in appropriate folder which is accessible to application.
Hope this helps.
I see this question asked many times about the ASP.NET style of application settings where the loading is done and then the code contains calls to ConfigurationManager.AppSettings["MySettingHere"] ..
..but my WinForms app doesnt use this method. Instead it uses the Project Settings route (i.e. I call Properties.Settings.Default.MySettingName to get my value, and I edit my settings by getting properties on the project and choosing the Settings tab)
App.config as a file is present in the root of the project/solution, but there is also Settings.settings and Settings.Designer.cs and I think these are the ones used and transformed into compiled code that gets the data
Essentially Visual Studio provides a type safe wrapper around the settings load/save/value getting process, and what I'd like to do is supply a path of the settings file to load rather than have it stuck at taking the default MyExeName.config file from the application directory
I assume you want to load custom configuration file from desired location rather than loading the default config, then try this,
NOTE : You can't have more than one App.config in a project.The app will use the config file named YourExcecutable.exe.config which is by
default the file App.config. But you can have multipe configuration
files and load then as you need using code. But you can't keep all of
them loaded at the same time. you can only switch between the files as
you need.
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap("path to new file");
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
OR
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #"Config file path");
The only solution I have found so far is rather a poor man's solve..
When we use the Settings tab inside a project's properties, the solution will gain a Settings.Settings, Settings.Designer.cs under the project's Properties node and possibly also an app.config in the root of the project. Edits to these files directly seem to be copied/updated /synchronised by VS itself. It also maintains some code in the background to ensure data-typed access to these settings. Likely it's based on Configmanager.AppSetings["propertyName"] but because VS is used to set up the property, and you tell it it's an int (or whatever) then VS can write wrapper code that exposes a namespace/class/member chain of ProjectNamespace.Properties.Settings.Default.PROPERTYNAME
Seemingly this code relies on the settingsfile being called THE_EXE_NAME.exe.config and being stored alongside the EXE itself..
..so I just take the the settings file that I want to use, copy it over the top of the one stored on disk, and call ProjectNamespace.Properties.Settings.Default.Reload() which does reload the values I want to use out of the new file. I can think of countless reasons why this isn't ideal but it's all I've been able to come up with so far
I need some setting of an application that will be shared among all users of the computer, but could also be changed at at run time. That seam simple, but according to the Application Settings MSDN article, it's either one or the other.
There are two types of application settings, based on scope:
Application-scoped settings can be used for information such as a URL for a Web service or a database connection string. These values are associated with the application. Therefore, users cannot change them at run time.
User-scoped settings can be used for information such as persisting the last position of a form or a font preference. Users can change these values at run time.
I could write code to edit the app.config XML file, but since it's located in the program directory, it's protected under windows 7. So this is not possible without elevating the program or playing with NTFS rights.
So I need the configuration file to be written in a common folder like System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData).
But this is a fairly common requirement!
So, I'm wondering if there a simple way of achieving this without reinventing the wheel, or if I have to write my own Setting Manager.
After reading the answers here and playing with the ConfigurationManager.Open methods I ended up with the following:
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyApp", "MyApp.config");
Configuration MyAppConfig = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = path }, ConfigurationUserLevel.None);
The nice part is the file doesn't have to exist, and if you call Save() on it, it will create the folder and the file for you. AppSettings["key"] didn't work though so I had to use
MyAppConfig.AppSettings.Settings["key"].Value
to read and write an existing value and
MyAppConfig.AppSettings.Settings.Add("key", value)
to add a new value.
I have had a similar problem and ended up writing my own settings class. It was very basic. I created a Settings class with the properties I needed, and a SettingsManager with Save() and Load() methods that simply serialized/deserialized the object via XmlSerializer into/from a file.
Yes, it is your own code, but it is very simple code, takes less time than trying to figure out whether there is a component providing what you need and how to customize it.
The Application Settings infrastructure does not support this - only non-editable application data and user-scoped data are supported. You can easily read and write your own XML into the CommonApplicationData folders, however, instead of using the application data.
I am writing a program that will be running continually on a server. I would like to be able to change some of the inputs without hard coding requiring recompiling.
I know this is possible to do by using a text file, however I don't want to have a text file for each value.
I also know that I could use a table, but I also don't want to have a table with one row for this program.
Is there another solution?
As you can probably guess, I am new to the .NET/C# world, so pardon if this is too basic of a question.
Use the appsettings section of the app.config.
Depending on what you are trying to accomplish, Application Settings may also serve your needs. These are stored on the client computer. You can save user settings here, for example.
My preference is most cases is App.config (Web.config in ASP.NET), though, as has been suggested by other replies.
It sounds like you need one or more Config files, C# has built in support for an XML formatted Config File App.Config the access point to which lives in System.Configuration.ConfigurationManger.AppSettings
You have many possibilities:
Text file with separated values
XML file with element values
Web.config if your program is ASP.NET
App.config
Database (But not in your case)
Web Service from another program to (Maybe overkill)
Hard coded values in html (non compiled file)
The easiest is Web.config or App.config because .net have already tools for you when you want those values : ConfigurationSettings.AppSettings["Key"];
Not really clear what are you trying to acomplish but if i understood well you want a value in your program to change dynamically.
If thats the case you can use xml configuration the XmlReader and XmlWriter class in the System.Xml namespace.
When you compile a C# project, the app settings from app.config are saved along with the exe file. For example, if the program name is "solve_np.exe", there will be a "solve_np.exe.config" next to it, making it look less neat than I want it to. How can you embed it into the .exe?
I tried to set Build Action to Embed Resource, but that did not do the trick.
Aha. I guess you're falling foul of Visual Studio automatically placing stuff in configuration that you DONT want configured by the end user.
In this case use resources. Simply add a new file of type .resx. With this you'll be able to add things like strings and images to the resource file. After you build this it should provide static access to the resources (it typically generates a code file from the resources for you so you don't have to access ResourceManager yourself).
E.G. If I made resources.resx with a string called MyConfigValue after a build I should be able to access this like:
textBox.Text = Resources.MyConfigValue;
If you want values that are kinda variable but shouldn't be configurable then this is the right place to put them.
HTH.
It isn't unprofessional to have an app.config file shipped alongside your exe. I think the word you may be looking for is untidy. I personally don't find this is the case myself however everyone is different! Perhaps you could simply make the app.config file hidden by default?
Or another alternative is to create your own config file which you could save to the App Data folder or even storing the settings in the registry instead.
Here's another factor to consider. Seasoned .Net developers are accustomed to the standard application design, which incorporates using config files in both web apps and desktop apps. If you depart from that practice, you will make it more difficult for any developers who follow you to understand what you have done. Even sa's on the web server may be confused by the absence of a config file.
Since pretty much everybody does it this way, your code does not look "untidy" to others. On the contrary, it would be befuddling not to see a config file where one is expected.
Typically the theory of a configuration file, is that it stores settings you may want to change once you've deployed the application (for something like user preferences). To do this, you need to be storing somewhere external to your application. If you use the default setup, you get "[Your].exe.config". There are many other options you could look at, but nearly every one of them ends up with a file written somewhere, if you providing a mechanism that saves settings of some kind.
I agree with serhio darasd and Quibblesome but you can just delete "solve_np.exe.config" and it'll just use default configs.
After considering what was written in these comments and other searching, I decided that the best way to handle my issue of wanting my Entity Framework connection string to be embedded into my executable instead of needing the MyApplication.exe.config file with my deployed solution was to created a derived class like such:
Public Class MyEFDataContainerLocal
Inherits MyEFDataContainer
Public Sub New()
MyBase.New(My.Settings.MyEFContainerConnectionString)
End Sub
End Class
I just created an Application Setting of type Connection String that contained the same string as what is found in the App.Config file. I just had to replace the "e;'s with actual quotes.
Then whenever I wanted to use the MyEFDataContainer as in Dim db As New MyEFDataContainer I would just use Dim db As New MyEFDataContainerLocal instead.