我正在开发一个具有文本框的应用程序。我想将其内容写入文件,但我该怎么做呢?
问问题
12580 次
4 回答
3
有很多方法可以做到这一点,最简单的是:
using(var stream = File.CreateText(path))
{
stream.Write(text);
}
请务必查看 MSDN 页面中的File.CreateText
和StreamWriter.Write
。
如果您的目标不是 .NET Compact Framework,正如您的标签所建议的那样,您可以做的更简单:
File.WriteAllText(path, string);
于 2009-11-10T00:21:20.733 回答
2
System.IO.File.WriteAllText("myfile.txt", textBox.Text);
如果您对 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);
}
}
于 2009-11-10T00:21:56.707 回答
1
试试这个:
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);
}
}
当然,添加异常处理等。
于 2009-11-10T00:23:45.533 回答
0
对于richTextBox,您可以为此添加一个“保存”按钮。还从 Toolbox 添加一个 saveFileDialog 控件,然后在按钮的单击事件中添加以下代码。
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);
}
}
于 2011-04-03T06:53:40.043 回答