在C#中存储全局变量(如路径)的位置?
发布时间:2020-12-16 02:03:14 所属栏目:百科 来源:网络整理
导读:我是C#的新手,我仍在为某些事情找出最佳实践. 我想知道在哪里可以存储路径(例如文件上传)和其他各种变量等设置,以便可以在项目中的任何位置访问它们. 我应该只使用静态变量创建一个类,还是有更好的方法来存储这些设置? 解决方法 你最好将它保存在web.config
我是C#的新手,我仍在为某些事情找出最佳实践.
我想知道在哪里可以存储路径(例如文件上传)和其他各种变量等设置,以便可以在项目中的任何位置访问它们. 我应该只使用静态变量创建一个类,还是有更好的方法来存储这些设置? 解决方法
你最好将它保存在web.config中,因为这可以在编译后更改.
仅限web.config示例: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="DocumentDirectory" value="~/Documents" /> </appSettings> </configuration> 要么: web.config中: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings file="appSettings.xml" /> </configuration> 还有一个单独的appSettings.xml: <?xml version="1.0" encoding="utf-8" ?> <appSettings> <add key="DocumentDirectory" value="~/Documents" /> </appSettings> 你可以像这样read those settings: using System.Configuration; using System.Web.Configuration; Configuration config = WebConfigurationManager.OpenWebConfiguration(null); if (config.AppSettings.Settings.Count > 0) { KeyValueConfigurationElement customSetting = config.AppSettings.Settings["DocumentDirectory"]; if (customSetting != null) { string directory = customSetting.Value; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |