开发者

Where to save project related text files?

For testing and debugging purposes, I just hard-开发者_StackOverflow社区coded the file paths for the text files that would be used by my application, e.g.

const string CONFIG_FILE_PATH = @"C:\myconfigfile.txt";

But I don't think it's a good idea to leave it as it is in the Beta/Release version.

So I am wondering, what would be the best location for saving these configuration files that will be used / read by the application? Any suggestions?

Many Thanks.


Why not save the strings in the Settings section of your project? GRight click on your project in Solution Explorer, select Properties, go to the Settings section and add a new string with your file path. Then, in your code, you can access it like this:

using ProjectName.Properties;

var path = Settings.Default.MySetting;

To change the setting:

Settings.Default.MySetting = newPath;
Settings.Default.Save();


In the same folder as the executable.

But you should consider using a Settings class (you can read more here). Visual Studio can automatically create a strongly typed wrapper around a section in the app.config file. The settings are stored in the same file as the executable, but can be overridden (and saved from the application) in a matching file in the user profile for each user.


Another option: If the test config file is intended to sit along side your executable, you can "Add" "Existing Item..." to your project and then change its properties to "Copy always" or "Copy if newer". During debugging, the executable should be able to find the copy of the config in its current working directory.

This isn't such a useful solution when there's a lot of testing to do.


For settings I would certainly use the app.config file. This is proposed by Microsoft and apart from that it is pretty much the easiest way to handle application settings anyway.

For other files I'd recommend either the applications local or roaming settings path, depending on weather you only need the data local or not. For compact, local databases I tend to use this approach. The application directory, as suggested by Albin, is a bad idea. You cannot be sure that the user is actually allowed to write to that directory and/or files in that directory (i.e. the app was pre-installed by an admin with elevated rights).

To get the location of the local paths use

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)

and for the roaming path

 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming)

More information on Windows User Profiles (the actual paths in different versions of Windows for example, you can find here: http://msdn.microsoft.com/en-us/library/aa372123.aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜