将应用程序设置存储在项目文件夹中,而不是AppData.MyProperty生成的设置文件保存在以下位置C:UsersFooAppDataLocalMyAppMyApp.exe_Url_jknwq2raeohczydfp1loj02nf05zldfk1.0.0.0user.config问题是这不仅是用户特定的,还会导致程序为每个签名创建一个文件(debug/release等)提供了许多user.config文件,这会迫使开发人员用户在每次启动没有特定user.config的程序“版本”时重新填充整个设置。(如果我不够清楚,我会很乐意提供更多细节)我希望我的应用程序为所有用户提供一个单一的设置文件,而不考虑“版本”(调试/发布,否则)。这样,开发用户必须设置一次,并且每次启动应用程序时这些设置都有效,而无需为其他注册/用户重新输入。只需使用应用程序范围的设置。您可以像注册表中的所有高级程序一样保存和读取设置,方法如下:publicobjectGetRegistryValue(stringKeyName,objectDefaultValue)尝试{Microsoft.VisualBasic.Devices.Computerc=newMicrosoft.VisualBasic.Devices.Computer();Microsoft.Win32.RegistryKeyk=c.Registry.CurrentUser.OpenSubKey("Software\YourAppName",true);if(k!=null){res=k.GetValue(KeyName,DefaultValue);}else{k=c.Registry.CurrentUser.CreateSubKey("Software\YourAppName");}if(k!=null)k.Close();//exAsException}catch{//PromptMsg(ex)}returnres;}publicvoidSetRegistryValue(stringKeyName,object_Value){try{Microsoft.VisualBasic.Devices.Computerc=newMicrosoft.VisualBasic.Devices.Computer();Microsoft.Win32.RegistryKeyk=c。Registry.CurrentUser.OpenSubKey("Software\YourAppName",true);if(k!=null){k.SetValue(KeyName,_Value);}else{k=c.Registry.CurrentUser.CreateSubKey("Software\YourAppName");k.SetValue(KeyName,_Value);}如果(k!=null)k。关闭();//exAsException}catch{//PromptMsg(ex)}}另一种选择是创建一个可序列化类([Serializable()]attrib),其中包含所有设置作为属性,然后使用BinaryFormatter类将其保存在应用程序目录中publicvoidsaveBinary(objectc,stringfilepath){try{using(System.IO.Streamsr=System.IO.File.Open(filepath,System.IO.FileMode.Create)){System.Runtime.Serialization.Formatters。Binary.BinaryFormatterbf=newSystem.Runtime.Serialization.Formatters.Binary.BinaryFormatter();bf.Serialize(sr,c);sr.Close();}}catch(Exceptionex){抛出ex;}}publicobjectloadBinary(stringpath){try{if(System.IO.File.Exists(path)){using(System.IO.Streamsr=System.IO.File.Open(path,System.IO.FileMode).Open)){System.Runtime.Serialization.Formatters.Binary.BinaryFormatterbf=newSystem.Runtime.Serialization.Formatters.Binary.BinaryFormatter();对象c=bf.Deserialize(sr);sr.Close();返回c;}}else{thrownewException("找不到文件");}}catch(Exceptionex){抛出ex;}返回空值;}我设计了一个简单的解决方案,但有一些不足:publicvoidWriteLocalValue(stringlocalKey,stringcurValue){Configurationconfig=ConfigurationManager.OpenExeConconfiguration(Application.ExecutablePath);KeyValueConfigurationElementk=config.AppSettings.Settings[localKey];如果(k==null)config.AppSettings.Settings.Add(localKey,curValue);否则k.Value=curValue;配置.保存();}publicstringReadLocalValue(stringlocalKey,stringdefValue){stringv=defValue;尝试{配置配置=ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);KeyValueConfigurationElementk=config.AppSettings.Settings[localKey];if(k!=null)v=(k.Value==null?defValue:k.Value);返回v;}catch{返回defValue;问题:您需要UACassense来覆盖您的可执行配置,并且您不能使用Properties。Settings.Default.MyProperty语法我最终选择了一个更简单、更直接的替代方法,包括创建一个普通的Settings类并按此处所述对其进行序列化/反序列化。设置存储在项目文件夹中,而不是AppData中共享的所有内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
