简体   繁体   English

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

[英]how do you save from a savefile dialog in C#?

here is the code I am currently using to open a file using the openfiledialog `这是我目前用于使用 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();

` It allows me to open text files but I can't save changes nor create my own text file. ` 它允许我打开文本文件,但我无法保存更改或创建自己的文本文件。 no errors are shown during run time.运行时不显示任何错误。 Thanks again for the extra help.再次感谢您的额外帮助。

The SaveFileDialog doesn't do the actual saving for you; SaveFileDialog不会为您进行实际的保存; it simply allows the user to specify a file path.它只是允许用户指定文件路径。 You use the file path and then do the heavy lifting with an implementation of the StreamWriter class , something like:您使用文件路径,然后使用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 );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM