开发者

How do I compile my App.config into my exe in a VS2010 C# console app?

开发者 https://www.devze.com 2023-02-02 00:21 出处:网络
I\'m creating 开发者_开发技巧a console app in Visual Studio 2010 with c#. I want this app to be stand alone, in that all you need is the exe, and you can run it from anywhere. I also want to use app.c

I'm creating 开发者_开发技巧a console app in Visual Studio 2010 with c#. I want this app to be stand alone, in that all you need is the exe, and you can run it from anywhere. I also want to use app.config to store connection strings and so on.

My problem is that I can't seem to figure out how to include that app.config data into the compiled exe. I do see it creates appname.exe.config, but I don't want people to have to worry about grabbing two separate files when they get the app.

None of the googling I've done has come up with anything. Is this even possible?


You can't. Half the point of such config files is to allow changes to the configuration of the app outside of the app itself.

You would simply have to modify your program so that it didn't have a dependency on the app config file -- easiest way to do that would be to just stick the values inside your config into read only global variables.


I can see where you are going with this, but the answer might be a bit more complicated than you were looking for.

  1. Make app.config to be an embedded resource.
  2. Manually parse the app.config to get default app settings / connection strings / etc
  3. Still look for an app.config and override the defaults you read in earlier with the app.config values

This way you have some reasonable defaults that you don't have to maintain separate from you app.config as constants, you can run your app as just an exe, and you can still modify it at runtime by adding back in the app.config.

The one thing to remember, is that reading in the app.config from a resource won't give you the same behavior as the normal app.config. You are basically reading it in and using it by hand.


You mean you need to add it to the exe as a resource? Well, first of all you cannot, app.config is file based not resource based.

On the other hand, the only point of config file is that you can change it. Otherwise just hard-code or use constants.


As others have pointed out, the idea behind a configuration file is to avoid hard-coded values.

What you might do as an alternative is to to write a custom configuration section, with every element optional and with default values. That way anyone who can get by with the defaults doesn't need a config file. But if they need to override a default, they can provide one.

(Sorry, just a bit of brainstorming. I don't have an example available.)


Best workaround looks like to create it yourself at the application startup.

  1. Add App.Config as a resource, rename it to "App_Config"
  2. Check if config file exists
  3. If not, write default .config file

Example code:

Program.cs

    [STAThread]
    static void Main()
    {
        CreateConfigIfNotExists();
    }

    private static void CreateConfigIfNotExists()
    {
        string configFile = string.Format("{0}.config", Application.ExecutablePath);

        if (!File.Exists(configFile))
        {
            File.WriteAllText(configFile, Resources.App_Config);
        }
    }

Remember that it will only write your current config when building. It will not update it automatically when you deploy a new version. It will include the config as is when building. But this could be enough :)


Generally, you don't want to do this as your app.config provides a mechanism by which configuration may be done at runtime. As far as you specific goal (maintaining configuration outside of your code, but have it follow the binary), you have a couple of options:

  • Dynamically create a configuration file
  • Store the settings in the registry
  • Store the settings as resource strings within the console application

I am sure there are other, more creative, options available. My recommendation would be for the second option. When the application is first launched, create the necessary keys and set their default values from the executable. That way, if you need to do any debugging at a later date, you can simply run regedit and make any necessary changes without recompiling.


Please the first answer on this previous post - Configuration File as Embedded Resource


Like people are saying here the whole point of a config file is for modifying some settings outside the application. You can hard-code or use constants but you can also use the registry in windows if you want. That way you can make changes to the application and still only have a single exe file.

The code project has some good info about reading, writing and deleting from the registry. http://www.codeproject.com/KB/system/modifyregistry.aspx But be careful when editing the registry. Alot of applications are depending on it so you could destroy some settings if you do something wrong. I recommend reading and then doing.

public string Read(string KeyName)  {
RegistryKey rk = baseRegistryKey;
// Open a subKey as read-only

RegistryKey sk1 = rk.OpenSubKey(subKey);
// If the RegistrySubKey doesn't exist -> (null)

if ( sk1 == null )
{
    return null;
}
else
{
    try 
    {
        // If the RegistryKey exists I get its value
        // or null is returned.
        return (string)sk1.GetValue(KeyName.ToUpper());
    }
    catch (Exception e)
    {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
        return null;
    }
  }
}

public bool Write(string KeyName, object Value)  {
  try
  {
      // Setting
      RegistryKey rk = baseRegistryKey ;
      // I have to use CreateSubKey 
      // (create or open it if already exits), 
      // 'cause OpenSubKey open a subKey as read-only
      RegistryKey sk1 = rk.CreateSubKey(subKey);
      // Save the value
      sk1.SetValue(KeyName.ToUpper(), Value);
      return true;
  }
  catch (Exception e) {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Writing registry " + KeyName.ToUpper());
        return false;
    }
  }    

public bool DeleteKey(string KeyName)  {
  try
  {
      // Setting
      RegistryKey rk = baseRegistryKey ;
      RegistryKey sk1 = rk.CreateSubKey(subKey);
      // If the RegistrySubKey doesn't exists -> (true)
      if ( sk1 == null )
          return true;
      else
          sk1.DeleteValue(KeyName);
      return true;
  }
  catch (Exception e)
  {
      // AAAAAAAAAAARGH, an error!
      ShowErrorMessage(e, "Deleting SubKey " + subKey);
      return false;
  }
}

Of course this would only work on Windows. I assume that you are using Visual Studio so you are probably using Windows.

Happy coding and good luck!


IL Merge has lot issue with wpf executable also slow. I ended up using Cosura.Fody https://github.com/Fody/Costura and using command line parameter for passing my app config value. Also using iexpress http://en.wikipedia.org/wiki/IExpress to create final executable with command line args and exe merged together


Take a winform application for example, during compilation, a file 'xxx.EXE.config' will be generated along with the output EXE file. It will contain the 'app.config' settings. Distribute this as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消