在 C# .net 中序列化文本框

发布于 2024-12-22 18:14:06 字数 1128 浏览 2 评论 0 原文

我是.NET环境的初学者。 我有一个带有三个文本框和一个按钮的 Windows 应用程序。当用户单击按钮时,我希望所有文本框值以 XML 格式序列化到文件中。 我尝试这样做,

    DialogResult dr = new DialogResult();
    private void button1_Click(object sender, EventArgs e)
    {
        AddCustomer customer = new AddCustomer();
        customer.textBox1.Text = textBox1.Text;
        customer.textBox2.Text = textBox2.Text;
        customer.textBox3.Text = textBox3.Text;
        customer.textBox4.Text = textBox4.Text;

            saveFileDialog1.InitialDirectory = @"D:";
            saveFileDialog1.Filter = "Xml Files | *.xml";
            if (saveFileDialog1.ShowDialog().Equals(DialogResult.OK))
            {

                SerializeToXML(customer);
            }            
    }

    public void SerializeToXML(AddCustomer customer)
    {

           XmlSerializer serializer = new XmlSerializer(typeof(AddCustomer));
            TextWriter textWriter = new StreamWriter(@"D:\customer.xml");
            serializer.Serialize(textWriter, customer);
            textWriter.Close();
    }

这返回了 system.invalidoperationexception 是未处理的异常

有什么想法吗? 谢谢, 迈克尔

I am a beginner with .NET environment.
I have a windows application with three textboxes and one button. When the user clicks on the button, i want all the textbox values to be serialized in an XML format to a file.
I tried doing it this way,

    DialogResult dr = new DialogResult();
    private void button1_Click(object sender, EventArgs e)
    {
        AddCustomer customer = new AddCustomer();
        customer.textBox1.Text = textBox1.Text;
        customer.textBox2.Text = textBox2.Text;
        customer.textBox3.Text = textBox3.Text;
        customer.textBox4.Text = textBox4.Text;

            saveFileDialog1.InitialDirectory = @"D:";
            saveFileDialog1.Filter = "Xml Files | *.xml";
            if (saveFileDialog1.ShowDialog().Equals(DialogResult.OK))
            {

                SerializeToXML(customer);
            }            
    }

    public void SerializeToXML(AddCustomer customer)
    {

           XmlSerializer serializer = new XmlSerializer(typeof(AddCustomer));
            TextWriter textWriter = new StreamWriter(@"D:\customer.xml");
            serializer.Serialize(textWriter, customer);
            textWriter.Close();
    }

this returned system.invalidoperationexception was unhandled exception

any ideas?
Thanks,
Michael

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

回眸一笑 2024-12-29 18:14:06

您无法序列化控件,而是必须创建表示 TextBox 值的 Serialized 组件。 (有关更多详细信息,请阅读 MSDN 文章)。

例如,

[Serializable]
public class Customer
{
    public string Name { get; set; }
    public string Address {get;set;}
}

You can't serialize controls instead you have to create Serializable component that represent TextBox values. (For more detail read MSDN article).

For instance,

[Serializable]
public class Customer
{
    public string Name { get; set; }
    public string Address {get;set;}
}
倥絔 2024-12-29 18:14:06

您不应该序列化文本框对象,而只能序列化它们的值。
customer.textBox1 应该是字符串类型的 customer.text1。然后,您只需分配 customer.text1 = textbox1.text
另外,使用 [Serialized] 属性标记您的 AddCustomer 类。

编辑:这是我刚刚尝试过的代码,它工作正常。看看您是否可以使其在您的解决方案中发挥作用。

添加新类 Customer

[Serializable]
public class Customer
{
    public string FullName { get; set; }
    public string Age { get; set; }
}

尝试像这样序列化它

Customer customer = new Customer();
customer.FullName = "John"; // or customer.FullName = textBox1.Text
customer.Age = "21"; // or customer.Age = textBox2.Text

XmlSerializer serializer = new XmlSerializer(typeof(Customer));
TextWriter textWriter = new StreamWriter(@"D:\customer.xml");
serializer.Serialize(textWriter, customer);
textWriter.Close();

完成此操作后,我得到了一个使用以下内容创建的 xml 文件。

<?xml version="1.0" encoding="utf-8"?>
<Customer xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <FullName>John</FullName>
  <Age>21</Age>
</Customer>

尝试比较一下,看看自己做错了什么。

You shouldn't serialize the textbox object, only their values.
customer.textBox1 should be customer.text1 of type string. You then need to just assign customer.text1 = textbox1.text.
Also, mark your AddCustomer class with the [Serializable] attribute.

Edit: This is a code I just tried and it works fine. See if you can make it work in your solution.

Add new class Customer

[Serializable]
public class Customer
{
    public string FullName { get; set; }
    public string Age { get; set; }
}

Try to serialize it like this

Customer customer = new Customer();
customer.FullName = "John"; // or customer.FullName = textBox1.Text
customer.Age = "21"; // or customer.Age = textBox2.Text

XmlSerializer serializer = new XmlSerializer(typeof(Customer));
TextWriter textWriter = new StreamWriter(@"D:\customer.xml");
serializer.Serialize(textWriter, customer);
textWriter.Close();

After doing this, I got an xml file created with the following content.

<?xml version="1.0" encoding="utf-8"?>
<Customer xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <FullName>John</FullName>
  <Age>21</Age>
</Customer>

Try and compare to see what you are doing wrong.

峩卟喜欢 2024-12-29 18:14:06

在 .NET 中编写 XML 的方法有很多种。这是使用 XmlWriter 适用于非常简单的内容,例如本例:

string text1 = /* get value of textbox */;
string text2 = /* get value of textbox */;
string text3 = /* get value of textbox */;

// Set indent=true so resulting file is more 'human-readable'
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };

// Put writer in using scope; after end of scope, file is automatically saved.
using (XmlWriter writer = XmlTextWriter.Create("file.xml", settings))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("root");
    writer.WriteElementString("text1", text1);
    writer.WriteElementString("text2", text2);
    writer.WriteElementString("text3", text3);
    writer.WriteEndElement();
}

一个注意事项:您应该避免在 UI 线程上执行文件操作,因为这可能会导致阻塞行为(例如,磁盘可能会很慢并导致 UI 在写入时冻结)文件,或者它可能正在写入网络位置并在连接时挂起一段时间)。最好弹出一个进度对话框,并显示一条消息“文件正在保存中,请稍候...”,并在后台进行文件操作;一个简单的方法是使用 BeginInvoke将后台操作发布到线程池/<代码>EndInvoke


如果您想改用 XmlSerializer,则可以按照以下步骤操作:

  1. 创建一个 public 类型作为文档的根元素,并用 XmlRoot
  2. 添加由原始/内置类型或您自己的 public 自定义类型组成的元素/属性,这些类型也是 XML 可序列化的,并用 XmlElementXmlAttribute(根据需要)。
  3. 要写出数据,请使用 XmlSerializer使用适当的 StreamStreamWriterXmlWriter 以及根对象来序列化
  4. 要读回数据,请使用 XmlSerializer.Deseralize 使用适当的 StreamTextReaderXmlReader,转换返回值输入回您的根对象。

完整示例。

要序列化的类型:

[XmlRoot("customer")]
public class CustomerData
{
    // Must have a parameterless public constructor
    public CustomerData()
    {
    }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlElement("city")]
    public string City { get; set; }

    [XmlElement("company")]
    public string Company { get; set; }

    public override string ToString()
    {
        return
            "Name=[" + this.Name + "] " +
            "City=[" + this.City + "] " +
            "Company=[" + this.Company + "]";
    }
}

读取/写入数据的代码:

// Initialize the serializer to write and read the data
XmlSerializer serializer = new XmlSerializer(typeof(CustomerData));

// Initialize the data to serialize
CustomerData dataToWrite = new CustomerData()
{
    Name = "Joel Spolsky",
    City = "New York",
    Company = "Fog Creek Software"
};

// Write it out
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
using (XmlWriter writer = XmlTextWriter.Create("customer.xml", settings))
{
    serializer.Serialize(writer, dataToWrite);
}

// Read it back in
CustomerData dataFromFile = null;
using (XmlReader reader = XmlTextReader.Create("customer.xml"))
{
    dataFromFile = (CustomerData)serializer.Deserialize(reader);
}

Console.WriteLine(dataFromFile);

There are a lot of ways to write XML in .NET. Here is a way using XmlWriter that works for very simple content like in this case:

string text1 = /* get value of textbox */;
string text2 = /* get value of textbox */;
string text3 = /* get value of textbox */;

// Set indent=true so resulting file is more 'human-readable'
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };

// Put writer in using scope; after end of scope, file is automatically saved.
using (XmlWriter writer = XmlTextWriter.Create("file.xml", settings))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("root");
    writer.WriteElementString("text1", text1);
    writer.WriteElementString("text2", text2);
    writer.WriteElementString("text3", text3);
    writer.WriteEndElement();
}

One note: you should avoid doing file operations on the UI thread as this can result in blocking behavior (e.g. the disk can be slow and cause the UI to freeze up while it writes the file, or it could be writing to a network location and hang for a while as it connects). It is best to put up a progress dialog and display a message "Please wait while file is saved..." and do the file operation in the background; a simple way is to post the background operation the thread pool using BeginInvoke/EndInvoke.


If you want to use the XmlSerializer instead, then you would follow these steps:

  1. Create a public type to act as the root element of your document and mark it with XmlRoot.
  2. Add elements/attributes made of either primitive/built-in types or your own public custom types which are also XML serializable, marking them with XmlElement or XmlAttribute as necessary.
  3. To write the data out, use XmlSerializer.Serialize with an appropriate Stream, StreamWriter, or XmlWriter along with your root object.
  4. To read the data back in, use XmlSerializer.Deseralize with an appropriate Stream, TextReader, or XmlReader, casting the return type back to your root object.

Full sample.

The type to serialize:

[XmlRoot("customer")]
public class CustomerData
{
    // Must have a parameterless public constructor
    public CustomerData()
    {
    }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlElement("city")]
    public string City { get; set; }

    [XmlElement("company")]
    public string Company { get; set; }

    public override string ToString()
    {
        return
            "Name=[" + this.Name + "] " +
            "City=[" + this.City + "] " +
            "Company=[" + this.Company + "]";
    }
}

The code to read/write the data:

// Initialize the serializer to write and read the data
XmlSerializer serializer = new XmlSerializer(typeof(CustomerData));

// Initialize the data to serialize
CustomerData dataToWrite = new CustomerData()
{
    Name = "Joel Spolsky",
    City = "New York",
    Company = "Fog Creek Software"
};

// Write it out
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
using (XmlWriter writer = XmlTextWriter.Create("customer.xml", settings))
{
    serializer.Serialize(writer, dataToWrite);
}

// Read it back in
CustomerData dataFromFile = null;
using (XmlReader reader = XmlTextReader.Create("customer.xml"))
{
    dataFromFile = (CustomerData)serializer.Deserialize(reader);
}

Console.WriteLine(dataFromFile);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文