简体   繁体   English

保存用户输入以供以后使用C#

[英]Save User Inputs for Later Use C#

Howdee All, 豪迪

I have a C# VSTO Excel add-in that my organization uses to make various selections to pull data into Excel. 我有一个C#VSTO Excel加载项,我的组织使用该加载项进行各种选择以将数据提取到Excel中。 User interface is a windows form. 用户界面是Windows窗体。 There is a drop down box, which feeds a combo box with available parameters and the users select inputs there that define the parameters for the query. 有一个下拉框,它为组合框提供了可用参数,用户可以在其中选择定义查询参数的输入。 I display the parameters in a list box so the user can she what he/she selected. 我在一个列表框中显示参数,以便用户可以选择他/她选择的内容。 I've had a request to be able to save parameter inputs so users can quickly recall without having to put in same information over and over but not sure of the best way to do this. 我要求能够保存参数输入,以便用户可以快速调用,而不必一遍又一遍地输入相同的信息,但是不确定执行此操作的最佳方法。

Basically need to store the first drop down box and the parameters associated with it from the list box upon user request. 基本上需要根据用户要求从列表框中存储第一个下拉框和与之关联的参数。 Is creating a text file to save to the users PC the best way to go about this? 创建文本文件以保存到用户PC是解决此问题的最佳方法吗? I thought of creating a hidden tab to store them in Excel but then it's limited to that file. 我想到了创建一个隐藏的选项卡以将其存储在Excel中的方法,但此方法仅限于该文件。 I'm relatively new to C# so wasn't sure if there's a better way I'm not aware of. 我是C#的新手,所以不确定是否有我不知道的更好方法。

Cheers, Ryan 干杯,瑞安

As you're saying you don't want to limit them to their associated file, my approach would probably be to save this to the user's AppData folder, and use XML serialization. 就像您说的那样,您不想将它们限制为与其关联的文件,我的方法可能是将其保存到用户的AppData文件夹,并使用XML序列化。 You can see an example below. 您可以在下面看到一个示例。

The data will be in C:\\Users\\$user$\\AppData\\Roaming or ...\\Local depending on the AppData folder you pick. 数据将位于C:\\ Users \\ $ user $ \\ AppData \\ Roaming或... \\ Local中,具体取决于您选择的AppData文件夹。 See this for more info on that. 看到这个更多的信息。

Serializing: 序列化:

// this is just an example object, can do whatever you'd like here
var myObject = new MyObject()
{
    MyValue = "some data"
};

string path = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
    "MyExcelAddIn\\data.xml");

Directory.CreateDirectory(Path.GetDirectoryName(path));

var serializer = new XmlSerializer(typeof(MyObject));
using (var fileStream = new FileStream(path, FileMode.Create))
{
    serializer.Serialize(fileStream, myobject);
}

Deserializing: 反序列化:

string path = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
    "MyExcelAddIn\\data.xml");

MyObject myObject;
var serializer = new XmlSerializer(typeof(MyObject));
using (var fileStream = new FileStream(path, FileMode.Open))
{
    myObject = (MyObject)serializer.Deserialize(fileStream);
}
MessageBox.Show(myObject.MyValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM