简体   繁体   中英

How to give a folder path in app.config file in C#

I am creating an application in WPF.

  1. In that I am using XML file to store some settings.

  2. My app will run for every 10 sec. So it will use that XML file settings.

My issue is in My local system i am calling the XML file as D://Foldername/projectname/test.xml . But after deployment it is storing in C://Programfiles/Projectname/test.xml .

So how to give a generic path so that it runs in all the client systems. I am creating setup file to install in clients systems. Please help me.

  1. Open the project properties page.
  2. Click on Settings tab.
  3. Add a new item called "MyPath". Make it an Application Setting of type String and give it a sensible default path name as value.
  4. Reference the value in code with Properties.Settings.Default.MyPath .

If you open the applications config there will be a setting called MyPath where you can override the path at runtime.

I suggest you to put the XML file in the same folder as your EXE file and then use Assembly to get its current path.

var cfgPath = Assembly.GetExecutingAssembly().Location + ".config"

Update

it's better to name your config file the same with your exe file but with ".config" extension.

If you are really using ClickOnce , I hardly recommend you to create your own directory for data and configuration files:

private static string GetDataDir()
{
    var dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        "YourApplicationName");
    if (!Directory.Exists(dataDir))
        Directory.CreateDirectory(dataDir);
    return dataDir;
}

The problem with storing the data in the directory of the executable is, that it will be at a different location. While debugging, it will be in you \\bin directory. When the application is deployed by ClickOnce , you gonna have a bad time. The installation directory for a ClickOnce application is created for every version. So if you EVER update your application at "customers", all their settings will be lost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM