.net在两个程序之间共享配置数据
本文关键字:之间 程序 共享 配置 置数据 两个 net | 更新日期: 2023-09-27 18:17:26
我正在使用应用程序设置(作为Visual Studio的一部分),但似乎无法使用原始应用程序的设置获得其他应用程序。
有人可以帮助存储一些字符串变量之间的两个应用程序在。net c#?
编辑:似乎我需要添加一个参考到我的第一个应用程序从第二个应用程序访问属性。默认设置-我如何做到这一点?
如果你想在两个项目之间共享配置,你可以从其他项目中添加文件'as a link'
:右键单击项目>>选择'Add existing file'
>>导航到app.config文件>>单击add
按钮旁边的下拉菜单并选择add as a link
。
或
如果你想在两个应用程序之间共享配置,这是方法
我将有一个包含设置类的共享程序集。然后,您可以将该类序列化/反序列化到硬盘驱动器上的公共位置:
[XmlRoot()]
public class Settings
{
private static Settings instance = new Settings();
private Settings() {}
/// <summary>
/// Access the Singleton instance
/// </summary>
[XmlElement]
public static Settings Instance
{
get
{
return instance;
}
}
/// <summary>
/// Gets or sets the height.
/// </summary>
/// <value>The height.</value>
[XmlAttribute]
public int Height { get; set; }
/// <summary>
/// Main window status (Maximized or not)
/// </summary>
[XmlAttribute]
public FormWindowState WindowState
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Settings"/> is offline.
/// </summary>
/// <value><c>true</c> if offline; otherwise, <c>false</c>.</value>
[XmlAttribute]
public bool IsSomething
{
get;
set;
}
/// <summary>
/// Save setting into file
/// </summary>
public static void Serialize()
{
// Create the directory
if (!Directory.Exists(AppTmpFolder))
{
Directory.CreateDirectory(AppTmpFolder);
}
using (TextWriter writer = new StreamWriter(SettingsFilePath))
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
serializer.Serialize(writer, Settings.Instance);
}
}
/// <summary>
/// Load setting from file
/// </summary>
public static void Deserialize()
{
if (!File.Exists(SettingsFilePath))
{
// Can't find saved settings, using default vales
SetDefaults();
return;
}
try
{
using (XmlReader reader = XmlReader.Create(SettingsFilePath))
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
if (serializer.CanDeserialize(reader))
{
Settings.instance = serializer.Deserialize(reader) as Settings;
}
}
}
catch (System.Exception)
{
// Failed to load some data, leave the settings to default
SetDefaults();
}
}
}
你的xml文件将看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Height="738" WindowState="Maximized" IsSomething="false" >
</Settings>
如果你想让同一用户在两个应用程序中使用相同的设置,或者你想让所有用户共享相同的设置,除了标准的应用程序设置,你还有几个选择:
1)将数据存储在注册表中。您可以将设置设置为用户特定的或全局的机器。
2)将包含设置的结构化文件(如XML文件)保存在标准目录之一中:所有用户保存Environment.SpecialFolder.CommonApplicationData,单个用户保存Environment.SpecialFolder.ApplicationData。这就是我要使用的方法。