我正在尝试将文本从文本框导出到.txt文件。我找到了一些答案,但我无法让它工作。目前我有5个文本框,我想从中导出数据。我希望有一个易于阅读的标准格式。
这是我目前的代码:
private void totalaether_Click(object sender, EventArgs e)
{
aefirstNum = (!String.IsNullOrWhiteSpace(textBox2.Text)) ? Convert.ToInt32(textBox2.Text) : 0;
aesecondNum = (!String.IsNullOrWhiteSpace(textBox3.Text)) ? Convert.ToInt32(textBox3.Text) : 0;
aethirdNum = (!String.IsNullOrWhiteSpace(textBox4.Text)) ? Convert.ToInt32(textBox4.Text) : 0;
aefourthNum = (!String.IsNullOrWhiteSpace(textBox5.Text)) ? Convert.ToInt32(textBox5.Text) : 0;
op = "X";
if (op == "X") total = (((aefirstNum * 3) * 3) * 3) + ((aesecondNum * 3) * 3) + (aethirdNum * 3) + aefourthNum;
textBox6.Text = total.ToString();
}
所以这基本上是在文本框中写数字。我想要做的是取这些总数并将其输出为:
很棒:[这里的数字]
Pure:[数字在这里]
更大:[数字在这里]
常规:[数字在这里]
总计:[这里的数字]
工作解决方案这包括savefiledialog
,这允许我设置文本文件名并选择保存位置。
// set a default file name
exportAether.FileName = ".txt";
// set filters - this can be done in properties as well
exportAether.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (exportAether.ShowDialog() == DialogResult.OK)
{
using (var writer = new StreamWriter(exportAether.FileName))
{
writer.WriteLine("Brilliant: {0}", aefirstNum);
writer.WriteLine("Pure: {0}", aesecondNum);
writer.WriteLine("Greater: {0}", aethirdNum);
writer.WriteLine("Regular: {0}", aefourthNum);
writer.WriteLine("Total: {0}", total);
// write other lines here
}
感谢您的帮助,这非常有效!
答案 0 :(得分:5)
一种方法:
using (var writer = new StreamWriter("filename.txt"))
{
writer.WriteLine("Brilliant: {0}", aefirstNum);
writer.WriteLine("Pure: {0}", aesecondNum);
// write other lines here
}