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

前端 未结 10 1941
傲寒
傲寒 2020-12-05 17:24

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

10条回答
  •  一向
    一向 (楼主)
    2020-12-05 18:20

    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 :)

提交回复
热议问题