C# Streamreader:处理特殊字符 \" \' ETC

发布于 2024-12-29 16:25:16 字数 626 浏览 0 评论 0 原文

我正在阅读然后写入一个文本文件。在感兴趣的数据之前和之后,文件包含许多应保持不变的行。但 StreamReader 似乎将特殊字符 ( " ' ) 转换为其他字符,这些字符在 C# 文本框和记事本中显示为时髦的菱形。文本如何通过文件读/写操作完全不改变?

StreamWriter sw = new StreamWriter(sOutputFileName);
using (StreamReader sr = new StreamReader(sTempFileName))
{
   while (sr.Peek() >= 0)
   {
       rdBuffer = sr.ReadLine();
       txtProgressDisplay.Text += rdBuffer + "\r\n";

       // parse and process some lines here

       wrBuffer = rdBuffer;
       sw.WriteLine(wrBuffer);
       txtProgressDisplay.Text += wrBuffer + "\r\n";
   }
   sr.Close();
}
sw.Close();

I'm reading then writing a text file. Before and after the data of interest the file contains many lines that should remain unaltered. But streamreader seems to convert the special characters ( " ' ) into other characters that appear as funky diamonds in both C# textboxes and in notepad. How can text get passed through file read/write operations completely unaltered? Thanks.

StreamWriter sw = new StreamWriter(sOutputFileName);
using (StreamReader sr = new StreamReader(sTempFileName))
{
   while (sr.Peek() >= 0)
   {
       rdBuffer = sr.ReadLine();
       txtProgressDisplay.Text += rdBuffer + "\r\n";

       // parse and process some lines here

       wrBuffer = rdBuffer;
       sw.WriteLine(wrBuffer);
       txtProgressDisplay.Text += wrBuffer + "\r\n";
   }
   sr.Close();
}
sw.Close();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看海 2025-01-05 16:25:16

我几乎可以肯定该问题与字符编码有关,即 UTF8、ASCII、UTF7 等。尝试创建传入正确编码的 StreamReader

StreamReader sr = new StreamReader(sTempFileName, System.Text.Encoding.ASCII);

您可以使用 Encoding.ASCIIEncoding.UTF7

I am almost certain the issue is related to character encoding, ie UTF8, ASCII, UTF7, etc. Try creating your StreamReader passing in the correct encoding,

StreamReader sr = new StreamReader(sTempFileName, System.Text.Encoding.ASCII);

You can use Encoding.ASCII, Encoding.UTF7, etc

悲喜皆因你 2025-01-05 16:25:16

你的问题似乎与编码有关。

1) 检查您的文本查看器是否使用与 .NET 应用程序相同的编码(也许是 UTF-8?)。

2) 检查文件本身是否也是使用与 .NET 应用程序相同的编码创建的(您是否混合了不同编码的字符?)。

Your problem seems to be something with encoding.

1) Check that your text viewer is using the same encoding as your .NET application (maybe UTF-8?).

2) Check if the file itself has been created using the same encoding as your .NET application too (are you mixing characters in different encodings?).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文