How do you embed app.config in C# projects? - c#

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 &quote;'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.

Related

How to get an Application Settings shared to all users that could be changed at run time

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.

Change data without recompiling in C#

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.

single exe with changeable settings

I am trying to make a simple application which will be used to point a web browser control to some of our web applications at my work. I would like to have only one exe file but also have an admin window to change some of the settings and have them persist when the application is closed. Is that possible? I have looked at the application settings resources part but as I understand that makes a file that loads the settings.
I don't want to have to parse a file or have anything but ONE file so please don't suggest doing that if it is possible.
Just use application settings - that will create a single file, you won't have to do any parsing, it'll all be fine.
It'll be separate to the exe file, but unless you meant that "ONE file" to include the executable and rewrite that on the fly, it should fit your description easily.
For example, let's build a console app that just remembers how many times it's been launched:
Create a new console application project
Go to the properties page, and click into the Settings tab.
Click on the link to create a settings file
Type in the table to create a setting called "LaunchCount" of type int. Make it either user scope or application scope, depending on whether you want it to be persisted per user or system-wide.
Hit Ctrl-S to save.
In the Main method in Program.cs, write this code:
Settings settings = Settings.Default;
settings.LaunchCount++;
Console.WriteLine("Launch count: {0}", settings.LaunchCount);
settings.Save();
Add the appropriate using directive for Settings (put the cursor in Settings and hit Ctrl-.)
Run the app several times, and observe the number increasing.
You can't have persisted settings without having a separate file...safely. You must either have a separate file, which is the standard and suggested approach approach, like the one created with Application settings, or you must use something like the registry to save settings.
Keep in mind, though, that using the registry is highly discouraged due to security reasons. Plus most companies don't allow access to registries anyway which means that anyone without this access could not use the settings feature.
There are several ways to do this. You can use a command-line argument to do that. Launch the app from the shell and put in your command line argument and change how it launches.
A UNIX-y approach is to look at the name of the exe and change behavior based on that. If I recall correctly, rsh and rlogin are the same executable - they just look at argv[0] to decide how to run. In windows, this is straight forward - look at System.Environment.GetCommandLineArgs - if there is a non-empty string in the 0th element of that, it will be your executable name.
For persisting settings, see Jon Skeet's answer.
I have to say that this is generally a bad idea, but I've done this before a long time ago in VB6. I created a Resource within the exe and then (somehow) directly manipulated it.
The problem is, is that this is usually not possible within the .NET framework due to it being memory resident. These guys tryed it out in .net and they ended up creating an program in IL to do the heavy lifting... Modify Emdeded String in C# compiled exe
Go with a settings file as Jon suggested!

how to store settings for deployable c# application?

I want to store settings for my C# application, such that default setttings can be easily shipped with my binaries and the end-user can change them using a simple text editor(or in some other simple way).
I seem to face several alternatives : a .config file, .settings file or a .resx file. What are the pros and cons of these?
Edit1: End-users are computer professionals mainly, so editing these files should not be much of a problem.
Edit2: The settings are something like connection strings, and some other parameters (mostly one-time stuff). Building some kind of GUI/API for changing them is not really an option. Also my application will not edit any of these values, so persistence through code is not required.
Yes, Project + Properties, Settings tab was designed to do this. Add your settings here, change the Scope to Application. That generates a app.exe.config file in your build direcctory, deploy it along with your EXE. Use Properties.Settings.Default.SettingName in your code to obtain the setting value. Your user will normally need admin privileges to edit the .exe.config file on the target machine to change the setting value.
The small print: settings do not work well for DLL assemblies, you have to merge the .config files by hand. When using the debugger, settings are retrieved from the app.vshost.exe.config file.
The .settings file is a helper file used by the IDE, ignore it. .Resx files store resources, they get compiled and embedded in a binary form in an assembly. They are not editable by the user.
I think you can have two ways of doing this.
For regular users, you can make a custom GUI that will make it simple for them to use.
For advanced users, they can edit the configurations using a text editor if it's stored in a text file (ini file, config file, etc..) or you can make an API.
The .settings file is typically used for user-specific preferences and configuration information (whereas the .config file is used for global settings for the application or anything that modifies the .Net runtime. Simply putting parameters in a .config file can alter the behavior of your application even without you writing a single line of code for it).
Check out the Settings article on MSDN for more: http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx
Since the file will be modified by the users, I think using app.config is not a good idea. What if they break the file structure? Or set an invalid value? Probably your application will crash directly.
One of the solutions would be to use a custom XML file. You will then validate it when your application starts. XSD will probably be the more elegant way to do it, but you can also parse it directly and validate it in code. If the file is invalid, instead of crashing, you will try to solve the problem, and if impossible, display a pretty error to the user, explaining that there is an error in XML at line n, position n, which is [error description here].
If the end user is really going to be editing them, I'm not sure I would want them editing my app.config file.
You have another couple alternatives that you haven't included. You could use an old-school .INI file that is simpler for an end user to understand. You could also use the registry. I would recommend the INI file, unless your users are very savvy, in which case use the .config file.
The answer depends on the deployment method. For instance, if you are using ClickOnce and offer updates, you might encouter problems using Application Settings.
I believe the best way to go is to create a GUI, something that is most certainly suitable for novice users. Given that you already excluded that option, use John's suggestion (ini files).

C# Application Configuration Data

Hey, I want to store application configuration data. Currently, I'm using INIs but they are too old and now I want to try something new. I'm on .NET platform using C#.
What solutions do I have? app.configs?
The scenario here is like that, I want to let other programs read the configuration data.
Yes, the various .config files (app.config, web.config, etc..) have replaced INI and, to a certain extent, the Registry as the preferred means of storing configuration data for your application.
Any program, .Net or otherwise, can read those files. .Net has the ConfigurationManager class and other languages can simply do XML parsing to get the values they need.
The standard approach with .NET is to use app.config files for application settings and user.config files for user specific settings (the location varies between XP and Vista though).
There's nothing to stop other programs reading the configuration data, you just need to have a configuration setting in the second (or third) application that tells it where to look.
The app.config would be the preferred way of doing things in .NET. Should work fine to read from other applications as well, as long as you give them the right path to the file. And it's just an XML file, so you can read it from non .NET apps as well.
If you're using Visual Studio, you can use Application Settings for this purpose. Just open the automatically added Settings.settings or create another one. They will be automatically available in Properties.Settings.Default and are stored as XML. You can also have multiple settings files for different purposes.
This is a Visual Studio concept rather than a .NET concept.
I often use an SQL table to hold my application settings. I create a singleton class, ususally called AppSettings, that I load with data from the table. The AppSettings class is then used to get the config values instead of directly accessing the config files. For ASP.Net apps, I instantiate the AppSettings class in the Application_Start event in Global.asax.cs.
Doing this gives me a way to allow the user to control some of the app settings, e.g. an email address for notifications. It also can simplify things when maintaining prod, QA, and dev versions of the app (assuming you have separate database instances for each)

Categories

Resources