I have a question. This code open fine the txt files with english text, but when I trying to open the txt files with cyrillic text… the cyrillic symbols are “squares”. Is it possible to resolve this problem?
string fileData = openFileDialog1.FileName;
StreamReader sr = new StreamReader(fileData);
richTextBox.Text = sr.ReadToEnd();
sr.Close();
SavedFile = saveFileDialog1.FileName;
dataTextBox.SaveFile(SavedFile, RichTextBoxStreamType.PlainText);
Solution:
string fileData = openFileDialog1.FileName;
StreamReader sr = new StreamReader(fileData, Encoding.Default);
richTextBox.Text = sr.ReadToEnd();
sr.Close();
And you are SURE the file is UTF8, right? If you write string
str = sr.ReadToEnd();, place a breakpoint on the next line and watchstrin Visual Studio, you see cyrillic text right? Try opening the file in notepad, File->Save As and select UTF8 as encoding.The reason notepad is able to “read” the file is that it uses the user codepage, and in your case it’s probably the Windows-1251 (Cyrillic) Codepage.
StreamReadertries to read the file as UTF8. If you want you can forceStreamReaderto use a different codepage. The second parameter is theEncodingyou want to use. You passEncoding.GetEncoding(1251)for cyrillic. Sadly you must know theEncoding“a priori” (=before) reading the file.