[英]C#: Load *.txt to RichTextBox and convert into UTF8
I want to open text files and load them into a RichTextBox.我想打开文本文件并将它们加载到 RichTextBox 中。 This has been going fine so far, but now I'm struggling with an encoding issue.
到目前为止一切顺利,但现在我正在努力解决编码问题。
So I used the GetType() method from this StackOverflow page: How to find out the Encoding of a File?所以我使用了 StackOverflow 页面中的 GetType() 方法: How to find out the Encoding of a File? C# - and it returns "System.Text.UnicodeEncoding".
C# - 它返回“System.Text.UnicodeEncoding”。
My questions now are:我现在的问题是:
rtb.LoadFile(aFile, RichTextBoxStreamType.PlainText);
rtb.LoadFile(aFile, RichTextBoxStreamType.PlainText);
Instead of having the RichTextBox load the file from the disk, load it yourself, while specifying the correct encoding .不要让 RichTextBox 从磁盘加载文件,而是自己加载它,同时指定正确的编码。 (By the way,
Encoding.Unicode
is just a synonym for " UTF-16 little-endian ".) (顺便说一下,
Encoding.Unicode
只是“ UTF-16 little-endian ”的同义词。)
string myText = File.ReadAllText(myFilePath, Encoding.Unicode);
This will take care of the conversion for you.这将为您处理转换。 The string you get is encoded "correctly" (ie in the format used internally by .NET), so you can just assign it to the
Text
property of your RichTextBox.您获得的字符串已“正确”编码(即采用 .NET 内部使用的格式),因此您只需将其分配给 RichTextBox 的
Text
属性即可。
About your third question: The SaveFileDialog
is just a tool that lets the user choose a file name.关于您的第三个问题:
SaveFileDialog
只是一个让用户选择文件名的工具。 What you do with the file name (like: save some text into it, or encode some string and then save it) has nothing to do with the SaveFileDialog.您对文件名所做的操作(例如:将一些文本保存到其中,或对一些字符串进行编码然后保存)与 SaveFileDialog 无关。
The SaveFileDialog just allow you to choose the path where the file will be saved. SaveFileDialog 只允许您选择保存文件的路径。 It doesn't save it for you..
它不会为你保存它..
Use Encoding class to convert from an encoding to another.使用Encoding class 从一种编码转换为另一种编码。
And read this article for some example on how to convert and write it to a file.并阅读这篇文章,了解有关如何将其转换并写入文件的一些示例。
You can also use: richTextBox.LoadFile(filePath, RichTextBoxStreamType.UnicodePlainText);您还可以使用:richTextBox.LoadFile(filePath, RichTextBoxStreamType.UnicodePlainText);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.