Как сохранить из диалога сохранения файла в C #? - PullRequest
1 голос
/ 16 августа 2011

вот код, который я сейчас использую для открытия файла с помощью 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 Ответ

12 голосов
/ 16 августа 2011

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