【发布时间】:2022-08-19 01:55:31
【问题描述】:
我创建了一个程序,用户可以在其中输入一些信息,然后可以将所有内容保存到 xml 文件中,或者打开它。
在我设置更大规模的保存和打开内容之前,我创建了一个小型测试运行来寻找解决方案。有三个文本框,您可以在其中输入自己的信息,两个复选框和组合框,用户可以从几个选项中进行选择。我创建了一个打开和保存菜单条按钮,但想不出如何将所有这些信息保存到 xml.file 中。
using System;
using System.IO;
using System.Windows.Forms;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void openToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = \"c:\\\\\";
openFileDialog.Filter = \"XML-File | *.xml|All files (*.*)|*.*\";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
//Read the contents of the file into a stream
var fileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
}
}
//MessageBox.Show(fileContent, \"File Content at path: \" + filePath, MessageBoxButtons.OK);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = \"XML-File | *.xml|All files (*.*)|*.*\";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
/*private void validateUserEntry()
{
// Checks the value of the text.
if (textBox1.Text.Length == 0 && textBox2.Text.Length == 0 && textBox3.Text.Length == 0)
{
// Initializes the variables to pass to the MessageBox.Show method.
string message = \" AAAAAAAAAAAAA\";
string caption = \"Error Detected in Input\";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}*/
}
}
-
欢迎来到 StackOverflow。如果答案解决了您的问题,请将其标记为可接受的答案。如果它帮助你给它一个upvote。如果答案离题或根本没有帮助,请投反对票或添加评论。另见stackoverflow.com/help/why-vote
标签: c# .net xml visual-studio