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

men*_*dez 1 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();
Run Code Online (Sandbox Code Playgroud)

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

Ed *_* S. 12

SaveFileDialog不会为你做实际节能; 它只是允许用户指定文件路径.您使用文件路径然后使用StreamWriter类的实现来完成繁重的工作,例如:

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