你如何从C#中的保存文件对话框中保存?

时间:2011-08-16 00:01:31

标签: c# text save text-files savefiledialog

这是我目前用于使用openfiledialog“

打开文件的代码
    private void openToolStripMenuItem_Click_1(object sender, System.EventArgs e)
    {
        //opens the openfiledialog and gives the title.
        openFileDialog1.Title = "openfile";
        //only opens files from the computer that are text or richtext.
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        //gets input from the openfiledialog.
        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            //loads the file and puts the content in the richtextbox.
            System.IO.StreamReader sr = new
   System.IO.StreamReader(openFileDialog1.FileName);
            richTextBox1.Text = (sr.ReadToEnd());
            sr.Close();`                                                                                               here is the code I am using to save through a savefiledialog          `   

    Stream mystream;
    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();

        saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        saveFileDialog1.FilterIndex = 2;
        saveFileDialog1.RestoreDirectory = true;

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if ((mystream = saveFileDialog1.OpenFile()) != null)
            {
                StreamWriter wText = new StreamWriter(mystream);

                wText.Write("");

                mystream.Close();

`              它允许我打开文本文件,但我无法保存更改,也无法创建自己的文本文件。运行时没有显示错误。再次感谢您的额外帮助。

1 个答案:

答案 0 :(得分:12)

SaveFileDialog没有为您实际存款;它只是允许用户指定文件路径。您使用文件路径,然后执行繁重的StreamWriter class实现,如:

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    using( Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew) )
    using( StreamWriter sw = new TextWriter( s ) )
    {
        sw.Write( someTextBox.Text );
    }
}