序列化和反序列化特定属性

时间:2018-12-07 12:26:17

标签: c# forms serialization deserialization

我有一个名为UserConfigStorage的可扩展类。在此类中,我存储了有关用户的信息,这些信息是通过文本框输入的,这些文本框的格式为Workshop。如下:

课程

namespace PME
{

    [Serializable()]
    public class UserConfigStorage
    {
        public string userName, userCompany, userEmail;
    }
}

表格

namespace PME
{
    // there's also a lot more info that's hidden
    // because it's not relevant for the question

    UserConfigStorage userconfigstorage = new UserConfigStorage();
    userconfigstorage.userName = textBox1.Text;
    userconfigstorage.userCompany = textBox2.Text;
    userconfigstorage.userEmail = textBox3.Text;

    // serializing method
    public void SerializeUserConfig(string fileName)
    {
        FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        BinaryFormatter binForm = new BinaryFormatter();
        binForm.Serialize(fileStream, userconfigstorage);
        fileStream.Close();
    }

    // deserializing method
    public UserConfigStorage DeserializeUserConfig(string fileName)
    {
        FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryFormatter binForm = new BinaryFormatter();
        UserConfigStorage userconfigstorage = (UserConfigStorage)binForm.Deserialize(fileStream);
        fileStream.Close();
        return userconfigstorage;
    }
}

我的问题是:我将如何分别从文本框中序列化字符串(以便可以使用DeserializeUserConfig()分别访问它们)?还是可以将所有信息序列化为一个文件(例如.txt),然后访问所需的特定信息?

任何帮助或我应该研究的主题将不胜感激!

0 个答案:

没有答案