I'm learning C# and went through a text editor tutorial. The final result works pretty good, except there is something strange happening I do not understand.
When I write/save/load files all in the text editor they work fine. But whenever I write a file in a different editor/download a text file from the internet somewhere, the file fails to load.
When I load the file, I get
"An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll"
And when I look at "View Details" is says
"File format is not valid."
Even though there is text in the file (when viewed in a different text editor), the text property has nothing in it, a result of the file format being incorrect.
I'm pretty confused why it would load files made in the text editor itself (with the same extension) but not from somewhere else. I'm really not sure how to begin debugging this one. My save file/open file methods are listed below.
Open File
private void Open()
{
openFileDialog1.Filter = "RTF|*.rtf|Text Files|*.txt|VB Files|*.vb|C# Files|*.cs|All Files|*.*";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && openFileDialog1.FileName.Length > 0)
{
GetCurrentDocument.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
Save File
private void Save()
{
saveFileDialog1.FileName = tabControl1.SelectedTab.Name;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "RTF|.rtf";
saveFileDialog1.Title = "Save";
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (saveFileDialog1.FileName.Length > 0)
{
GetCurrentDocument.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
}
Help would be much appreciated, thanks!
It's not just the extension of the file that determines it's type. This version of the method allows loading both "regular" RTF files and also
ASCII
files.The RichTextBoxStreamType Enumeration provides a few different possibilities. If you are trying to load a file created using a different editor, you might need to use
RichTextBoxStreamType.PlainText
instead ofRichTextBoxStreamType.RichText
.