使用 StreamWriter 在文件中写入 Unicode 字符串不起作用
我有这段代码:
string s = "آ";
StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8);
writer.WriteLine(s);
但是当我运行它时,我在 a.txt 中看不到任何“Ë”! a.txt 中没有任何字符串!它是空的!有什么问题!!谁能帮我吗???
I have this code:
string s = "آ";
StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8);
writer.WriteLine(s);
but when I run it I can't see any "آ" in a.txt!! There isn't any string in a.txt! It is Empty! What is problem!?! Can anyone help me???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您永远不会
Close()
StreamWriter
。如果您在完成写入后调用 writer.Close(),您将看到该字符。
但是,由于它实现了 IDisposable,您应该将 StreamWriter 的创建包装在 using 语句中:
这将为您关闭流。
You never
Close()
theStreamWriter
.If you call
writer.Close()
when you finish writing, you will see the character.But, since it implements
IDisposable
you should wrap the creation of theStreamWriter
in ausing
statement:This will close the stream for you.
从外观上看,您不是
Flush ()
ing 或Close()
StreamWriter
。StreamWriter
在内部使用一个缓冲区,在关闭应用程序之前需要刷新该缓冲区,否则StreamWriter
超出范围,否则您写入的数据将不会写入光盘。完成后您可以调用
Close()
- 尽管我建议使用using
语句也可确保您的StreamWriter
得到正确处置。By the looks of it you're not
Flush()
ing orClose()
ing theStreamWriter
before you end your application.StreamWriter
uses a buffer internally which needs to be flushed before you close your application or theStreamWriter
goes out of scope otherwise the data you wrote to it will not be written to disc.You can call
Close()
once you're done - although instead I would suggest using ausing
statement instead to also assure that yourStreamWriter
gets properly disposed.尝试使用 File.WriteAllText("a.txt", s, Encoding.UTF8);。
Try using
File.WriteAllText("a.txt", s, Encoding.UTF8);
.一些提示:
查看如何:将文本写入文件
Few tips:
Check How to: Write Text to a File
接下来,使用正确的特殊字符将列表视图导出到 Excel 的完整功能:
Follow, complete function for export a listview to excel with correct special characteres:
如果您想从包含这些 Unicode 字符的某个位置读取文件,然后进行一些修改并写回该文件,就会出现问题。我遇到了同样的问题。这是对我有用的解决方案
从包含 Unicode 字符的文件中读取数据
我知道这不太漂亮,但它有效。
希望这有帮助!
If you want to read a file from somewhere that contains these Unicode characters then you do some modifications and write back to the file, the problem arises. I was stuck with the same problem. Here is the solution that worked for me
Reading data from a file that contains Unicode characters
I know this is not pretty but it worked.
hope this helps!