.net load configuration in class library

一世执手 提交于 2019-12-02 10:20:55

You cant do what you are trying to do - at least not the way you are going about it.

First, you have to understand how/where Settings are saved. With default naming of the app and such, project A - WindowsApplication1 will save its settings to something cryptic such as:

C:\Users\<UserName>\AppData\Local\Microsoft\_
    WindowsApplication1_Url_ggn13vigzyicmtfkwaa3vi5tyxn0sy3r\1.0.0.0\user.config

NET creates the hash to make sure that apps with the same name have a different safe location to store settings. So, WindowsApplication3 will have a different hash; this is also how your 17th project with the name WindowsApplication1 doesnt accidentally load or find the settings of WinApp 1-16.

Next, your Settings Class Lib is not a separate application. As a DLL, it is operating as if it was a set of functions and such associated with the App calling it. So when Project A saves settings thru the ClassLib, they are saved to a different location than Project B. Even using a Class Lib, NET uses Application credentials and info to concoct the filename and path.


What you can do is write a Class which defines all the possible settings (or creates a List or Dictionary of them) then save to a fixed, known location such as:

Private Comp As String = "ZiggySoft"
Private Prod As String = "ZiggyWare"

Private settingsFile As String

'...
settingsfile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
settingsfile = Path.Combine(settingsfile, Comp, Prod, "usersettings.dat")

This will result in: "C:\Users\\AppData\Roaming\ZiggySoft\ZiggyWare\usersettings.dat"

Include the same file in each project (Add Existing Item, maybe pick Add As Link from the dropdown). Now, you can read and write your Settings to a file you are in charge of. You can save/load the entire class or List in 3-5 lines of code if you serialize it.

When Project A loads the settings, it would also get those which only apply to B or J or V, but common ones would and could be shared.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!