سؤال

When I try to open my app config file by

ConfigurationManager.OpenExeConfiguration(filePath);

it returns an exception, because there is no file. But I need to create this file in this case. But as I know, config file create by adding at VS like How to: Add an Application Configuration File to a C# Project

So, how to create this file in other way?

هل كانت مفيدة؟

المحلول

If you really want to create an empty config file at runtime you can do something like this, but note that if the config file already exists this code will overwrite it:

System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
sb.AppendLine("<configuration>");
sb.AppendLine("</configuration>");

string loc = Assembly.GetEntryAssembly().Location;
System.IO.File.WriteAllText(String.Concat(loc, ".config"), sb.ToString());

نصائح أخرى

Just go to App.config file properties and change Copy to Output Directory setting from Do not copy to Copy always (or Copy if newer). That will automatically create config file during project build.

This file is needed by your application as you need to access it. The best way is to add it with Visual Studio as you wrote it. You have to ensure that it is properly deployed on the target machine at setup.

Then if it is not present on disk at runtime, it's a good behaviour to crash. You can display a message to the user (catch the exception).

Why would you want to create it any other way? Is it to make sure you always have a config file, even if the user deletes it? And why would a user do that? Oh never mind.

If you want to make sure there's always a config file, you can create it yourself if it isn't there:

if (!File.Exists(configFilePath)) ...

Config files are just XML. So you could create a new file and populate it with default data, right before you want to read a key from it.

However one would expect a user not to delete a config file. Just sayin'.

For those who are looking the answer in 2022, app.config will be created automatically if you will change the .NET Target Framework in Project properties

To add an application configuration file to a C# project

On the menu bar, choose Project > Add New Item.*

The Add New Item dialog box appears.

Expand Installed > Visual C# Items, and then choose the Application Configuration File template.

In the Name text box, enter a name, and then choose the Add button. A file named app.config is added to your project.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top