【问题标题】:Input with Streamreader doesn't give the same output in a StreamWriter使用 Streamreader 的输入不会在 StreamWriter 中提供相同的输出
【发布时间】:2014-12-08 11:07:38
【问题描述】:

我正在使用 StreamReader 读取文件,并使用 StreamWriter 将确切的行写入另一个文件。然而,我遇到的问题是,在生成的文件中,任何出现的字符 '¦' 都会转换为 '?'。

这是初始化我的流的代码:

using (var readFile = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    using (var writeFile = new FileStream(@"Modified\" +   Path.GetFileName(path), FileMode.Create, FileAccess.Write))
    {
        using (var sr = new StreamReader(readFile, new ASCIIEncoding()))
        {
            using (var sw = new StreamWriter(writeFile, new ASCIIEncoding()))
            {
                //Read line and write it to the writer
            }
        }
    }
}

这可能是流的问题还是更可能是原始文件的问题?原始文件本身在多个文本编辑器中显示得很好,所以看起来是正确的。

【问题讨论】:

  • 当你设置断点时,它在调试器中是什么样子的?
  • 你试过把编码改成UTF8吗?
  • 显然你实际上不喜欢使用 ASCIIEncoding。如果您不知道文本编码可能是什么,则选择 Encoding.Default。不过,你应该有一个线索。
  • 问题是,我确定它是 ASCII,因为 Unicode 不起作用。 Encoding.Default 确实有效。我不知道究竟是为什么。

标签: c# .net filestream streamreader streamwriter


【解决方案1】:

¦ 不是有效的 ASCII 字符,所以我假设原始文件不是 ASCII 编码的。将编码类型更改为 UTF 可以解决问题,但很难知道这是否符合您的要求。

using (var sr = new StreamReader(readFile, new UTF8Encoding()))
{
    using (var sw = new StreamWriter(writeFile, new UTF8Encoding()))

查看http://www.asciitable.com/ fpr 有效的 ascii 字符列表。

【讨论】:

  • 我检查了多个站点,这些站点给了我 166 作为 ¦ 的 ASCII 值,所以我认为它是 ASCII 集的一部分
【解决方案2】:

这可以通过使用 Encoding.Default 而不是 ASCIIEncoding 来解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多