[英]Save Contents Of a TextBox To a File
I'm developing an application that has a TextBox. 我正在开发一个具有TextBox的应用程序。 I want to write its contents to a file, but how can I do this? 我想将其内容写入文件,但是我该怎么做呢?
There are many ways to accomplish this, the simplest being: 有许多方法可以完成此操作,最简单的方法是:
using(var stream = File.CreateText(path))
{
stream.Write(text);
}
Be sure to look at the MSDN page for File.CreateText
and StreamWriter.Write
. 确保查看MSDN页面上的File.CreateText
和StreamWriter.Write
。
If you weren't targeting the .NET Compact Framework, as your tags suggest, you could do even simpler: 如果您没有针对.NET Compact Framework,如标签所示,则可以做得更简单:
File.WriteAllText(path, string);
System.IO.File.WriteAllText("myfile.txt", textBox.Text);
If you're stuck on some brain-dead version of the BCL, then you can write that function yourself: 如果您被困在一些脑筋急转弯的BCL版本上,那么您可以自己编写该函数:
static void WriteAllText(string path, string txt) {
var bytes = Encoding.UTF8.GetBytes(txt);
using (var f = File.OpenWrite(path)) {
f.Write(bytes, 0, bytes.Length);
}
}
Try this: 尝试这个:
using System.Text;
using System.IO;
static void Main(string[] args)
{
// replace string with your file path and name file.
using (StreamWriter sw = new StreamWriter("line.txt"))
{
sw.WriteLine(MyTextBox.Text);
}
}
Of course, add exception handling etc. 当然,请添加异常处理等。
For a richTextBox, you can add a "Save" button for this purpose. 对于richTextBox,您可以为此添加一个“保存”按钮。 Also add a saveFileDialog control from Toolbox, then add following code in button's click event. 还可以从工具箱中添加一个saveFileDialog控件,然后在按钮的click事件中添加以下代码。
private void button1_Click(object sender, EventArgs e)
{
DialogResult Result = saveFileDialog1.ShowDialog();//Show the dialog to save the file.
//Test result and determine whether the user selected a file name from the saveFileDialog.
if ((Result == DialogResult.OK) && (saveFileDialog1.FileName.Length > 0))
{
//Save the contents of the richTextBox into the file.
richTextBox1.SaveFile(saveFileDialog1.FileName);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.