开发者

Migrating a WinForms (C#) APP settings to a .config file

开发者 https://www.devze.com 2022-12-13 11:43 出处:网络
I want to migrate the settings file I am currently using to appconfig file. At the moment I am trying to make a copy of it but so far I cannot even get it t开发者_开发问答o write to the file using the

I want to migrate the settings file I am currently using to appconfig file. At the moment I am trying to make a copy of it but so far I cannot even get it t开发者_开发问答o write to the file using the Config' Manager.

What I need to do is first create the file and then write to it and finally of it already exists, update it!. Seems pretty simple but so far its eluding me at every turn. All the materials I have referred to so far ALL ASSUME it exists. Even the MS MCTS reference book has a config file already made for the examples.

Is there a programmatic way of creating it and then writing to the default bin folder of the application assuming you have sufficient privileges.

The examples make this look soo simple but when you look at the timestamps on the file in question ....scratches his head ... hat falls !

I mean are they different types of config files? I know of web.config and app.config but how much do people really deviate from this simple naming template???

Thanks for any replies. Ibrar


First of all, You say app.config is a config file. It is not. It is the source file within Visual Studio that is used by VS to create the config file during compilation. During Compilation, if Visual Studio detects an app.config, it copies it to the output folder of the compilatuion and renames it to (assuming the fully qualified name of your assembly is NameSpace.your.applicationName),

NameSpace.your.applicationName.exe.config

That is the file you should be looking for, and reading/writing to in any custom code you are writing.

As other answer mentions, be careful doing this. it is not trivial. this file is only a portion of a complete system that the CLR uses to manage configuration for your application, and you can mess it up easily.

FInally, please investigate the config file element called configSource. Using this, you can place an element in your app.config that "redirects" the configuration system to look in a separate file for a specific config section. You would use it by modifying the section element in the app.config like this:

<MyConfigSectionName configSource="ConfigFolder\MySpecConfigFile.xml" />

or, to move an existing .Net config section to a separate file,

<appSettings configSource="ConfigFolder\MyAppSettings.xml" />

Then you can create a separate config file with the settings you want in it, and open, read, and write to that file...

contents of file MyAppSettings.xml:

<?xml version="1.0" encoding="utf-8" ?>

<appSettings>
  <add key="limitToSingleInstance" value="true"/>
  <add key="maximumCacheFiles" value="1000"/>
  <add key="maximumThreadCount" value="5"/>
</appSettings>


Here is an example of how to create a custom config file, store some configuration data, and then read it back along with some if exists statements to create it if it needs to be. Hopefully it won't be that much trouble to translate it into C#.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If System.IO.File.Exists(System.IO.Directory.GetCurrentDirectory() + "\Settings.Config") Then
        FileOpen(1, System.IO.Directory.GetCurrentDirectory() + "\Settings.Config", OpenMode.Random, OpenAccess.ReadWrite)
        FileGet(1, SettingVar1, 1)
        FileGet(1, SettingVar2, 2)
        FileGet(1, SettingVar3, 3)
        'etc
        FileClose(1)
    Else
        FileOpen(1, System.IO.Directory.GetCurrentDirectory() + "\Settings.Config", Openmode.Random, OpenAccess.ReadWrite)
        FilePut(1, "Static Setting to write", 1) 'insert a string
        FilePut(1, 3, 2) 'insert a number
        FilePut(1, New DBMC, 3) 'Any object
        'etc...
        FileClose(1)
    End If
End Sub

It should probably be noted that .NET has a built in Settings file that VB can reference (My.Settings) that would do the same thing as this but without the overhead of managing the file through code. There is also the registry for saving settings variables (if you're feeling brave and promise to clean up the registry when your program gets uninstalled), and many other correct ways of doing this.

Also, please note that many developers frown on using random access files and they are generally not used much anymore because of certain overhead costs associated with large random access files. However, for the sake of simplicity, a random access file is a very easy-to-understand way of creating and controlling a config file.


Got it working.

1) Firstly add a config file to your project.

2) Name or rename it to the name of application -like-for-like.

3) Make sure it ends with .config

4) Set the property on the config file so that it is copied out to the output folder.

5) Make sure your project correctly references the configuration assembly under project references.

6) Create the configuaration object like so for e.g:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

--> Stick with the "None" on the enumeration object for now ... experiment later for different users and etc.

7) Debug your project and run it a few times to make sure the config object is correctly picking up the config file and its file path property correctly points to the location of the config file. So at Run time this is going to be under \bin\debug\ .... -----> Check for the has ffile property also and make sure its true also.

8) At this stage, the config object is properly set-up and is ready to go. Now add your entries as though you were adding entries into a Hashtable or a Dictionary using the key-value pairs notion.

config.AppSettings.Settings.Add("Key", "Value");

9) Once you have added in some sample test data, last thing to do iss to save the config.

config.Save();

10) Finally, navigate to the build output folder and check to see if the file config file has changed.

UPDATE: You might find that vshost.exe file that ends up in the output directory might mess things up as I noticed my config object was pointed to one of these xml file and not my config file. Outside of the VS IDE this is O.K as the vhsost file is not deployed and not used but in the IDE its nice to get it all working in there. So follow my post below if this happens.

That was the answer I was more or less looking for ... Thanks for all the replies i got anyways.


i've scratched my head over the config files myself. In the end i have opted to simply create my own settings class and (de)serialize it as XML to/from disc as needed.

Considerations to serializing your own settings file:

  • More flexible
  • You have to write more code
  • Type safe (refer to setting by type rather than string ID)

Tons of other considerations of course, but the third is my fave.


Even though this is not answer but a follow up from the previous post.

private void saveAllMenuItem_Click(object sender, EventArgs e)
    {
        // Set up the config object .... with a default user level.
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        if (isWindowsDriveSet())
        {
            // Save the drive name and write it to a config file.
            config.AppSettings.Settings.Add("Drive", WindowsDrive());
        }
        else
        {
            MessageBox.Show("Please set your windows drive before proceeding!", "Windows Drive Not Set!",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        if (ShowHiddenFilesSetting()) // only true (executes) if the app is showing 'ALL' files.
        {
            config.AppSettings.Settings.Add("FileSettings", FileSettings());
        }
        else // else default is implied.
        {
            config.AppSettings.Settings.Add("FileSettings", FileSettings());            
        }

        // Notify the user that the method has completed successfully.
        toolStripStatusLabel.Text = "Settings saved.";

        // Log to the logger what has just happened here.
        ActionOccured(this, new ActionOccuredEventArgs("0", DateTime.Now.ToString(), "The user has saved his settings."));

        // Finally save to the config.
        config.Save();
    }

Above is my 'Save()' method that saves application settings. While I did manage to get it working ... i found that after testing and wiping my area down on each build I found that rather my application automatically look for 'MyFileExplorer.config' it instead looks for a vshost.exe.config file of some sort. I have no idea why it is looking for this file? As the filePath property is an accessor property so I can't change it's value.

I will experiment further see if i can get it to work again !

0

精彩评论

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