使用.txt扩展名创建文件(C#)

Ann*_*Bot -1 c# io save

我正在尝试使用我的程序创建.txt文件并在其中保存richtextbox的内容(或者只是编辑现有文件,但这已经有效).问题是,当我保存尝试保存文件时,它会创建文件但没有.txt扩展名.我尝试了几件事,包括以下两件事,但都创建了一个没有扩展名的文件.我怎样才能解决这个问题?

            SaveFileDialog op = new SaveFileDialog();
            op.Title = "Save";
            op.Filter = "Text Document(*.txt)|*txt";
            //op.DefaultExt = "txt";
            //op.AddExtension = true;

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

和:

   SaveFileDialog op = new SaveFileDialog();
   op.Title = "Save";
   op.Filter = "Text Document(*.txt)|*txt";
   if (op.ShowDialog() == DialogResult.OK)
   {
       richTextBox1.SaveFile(op.FileName, RichTextBoxStreamType.PlainText);
       filename = op.FileName;
       this.Text = op.FileName;
   }
Run Code Online (Sandbox Code Playgroud)

Sim*_*ead 7

您需要在扩展名前面添加一个点:

op.Filter = "Text Document(*.txt)|*txt";
Run Code Online (Sandbox Code Playgroud)

所以它变成了这样:

op.Filter = "Text Document(*.txt)|*.txt";
Run Code Online (Sandbox Code Playgroud)