簡體   English   中英

如何從 C# 中的保存文件對話框中保存?

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

這是我目前用於使用 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();

` 它允許我打開文本文件,但我無法保存更改或創建自己的文本文件。 運行時不顯示任何錯誤。 再次感謝您的額外幫助。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM