问题
I'm trying to create a simple notepad for my self. At the moment i have created a button where i can Open file and get content. How can i create a Save file button so every line of my richboxtext goes to new .txt file?
I want that i can save to a file name of my choice not a static one so i use SaveFileDialog.
This is what i have for Open File.
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
Stream plusma = openFileDialog1.OpenFile();
string faila_nosaukums = openFileDialog1.FileName;
string faila_teksts = File.ReadAllText(faila_nosaukums);
rtf_NotePad.Text = faila_teksts;
}
Nothing up for Save file at the moment:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
}
----------Updated-----------------
Saving file:
saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
saveFileDialog1.AddExtension = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtf_NotePad.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
Adding color:
colorDialog1.ShowDialog();
rtf_NotePad.ForeColor = colorDialog1.Color;
回答1:
You can use the RichTextBox.SaveFile() method:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtf_NotePad.SaveFile(saveFileDialog1.FileName);
}
Also, there exists a similar method for opening the file. It is the RichTextBox.LoadFile() method. Use it like this:
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
rtf_NotePad.LoadFile(openFileDialog1.FileName);
}
回答2:
You can use SaveFile(String, RichTextBoxStreamType) method of your rich text box and and pass RichTextBoxStreamType.PlainText
as second parameter.
Also if you want to let the user choose to save in .txt
format or .rtf
:
var saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
saveFileDialog.AddExtension = true;
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var extension = System.IO.Path.GetExtension(saveFileDialog.FileName);
if(extension.ToLower()==".txt") /*saveFileDialog.FilterIndex==1*/
richTextBox1.SaveFile(saveFileDialog.FileName, RichTextBoxStreamType.PlainText);
else
richTextBox1.SaveFile(saveFileDialog.FileName, RichTextBoxStreamType.RichText);
}
You should know .rft
format is different from .txt
format.
If you save in .rtf
format, the formatting including font and color remains, but if you save in .txt
format, it only saves the plain text. And if you want to simulate notepad, you don't need to use .rtf
format.
Another point is if you want to have only the Font
option like notepad, the font option would be a User Settings
that can be saved via Settings.settings
. Then you can set that font for your TextBox
/RichTextBox
after application loads. This way you can save the file in .txt
format.
来源:https://stackoverflow.com/questions/34568883/how-to-save-richboxtext-content-to-txt-file-via-savefiledialog