2009-11-10 68 views

回答

3

有很多方法可以做到这一点,最简单的幸福:

using(var stream = File.CreateText(path)) 
{ 
     stream.Write(text); 
} 

一定要看看MSDN页File.CreateTextStreamWriter.Write

如果你不面向.NET Compact Framework的,因为你的标签建议,你可以做更简单:

File.WriteAllText(path, string); 
+0

感谢您的示例和阅读指示,主要是因为适应症!继续这样! ;) – 2009-11-10 00:59:54

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); 
    } 
} 
+0

+1不能比这更容易! – James 2009-11-10 00:22:24

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); 
    } 
} 

当然要加异常处理等

+0

杜! '使用'*是*异常处理! – 2009-11-10 00:27:08

+0

我的意思是一些'try-catch'短语让用户知道a。该文件不能创建b。他没有权限c。文本框为空等 – 2009-11-10 17:26:08

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); 
    } 
} 
相关问题