c# StreamReader或String读取的字符比要求的多

本文关键字:字符 String 读取 StreamReader | 更新日期: 2023-09-27 18:15:07

我很难理解字符串是什么。子字符串方法正在做什么。这是我的代码(它是一个香草VisualStudio c#控制台应用程序与一些由我添加的代码):

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace foo {
class Program
{
    static void Main(string[] args)
    {
        String pathToFile = "the-path-to-the-file";
        using (StreamReader streamReader = new StreamReader(pathToFile))
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("encoding = " + streamReader.CurrentEncoding);
            String fileContents = streamReader.ReadToEnd();
            Console.WriteLine("encoding = " + streamReader.CurrentEncoding);
            String substring = fileContents.Substring(0, 35);
            Console.WriteLine("substring length = " + substring.Length);
            Console.WriteLine("substring = " + substring);
            Console.OutputEncoding = System.Text.Encoding.Default;
            Console.WriteLine("encoding = " + streamReader.CurrentEncoding);
        }
    }
}
}

在pathToFile中找到的文件包含:

从殲c´ƒ»一ƒ€,¦ƒ«一ƒ€ƒ——ƒ©.endxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

,十六进制是:

00000000h: 66 72 6F 6D E6 AE B2 E7 90 B4 E3 83 BB E3 83 80 ; from殲ç´ãƒ»ãƒ€
00000010h: E3 82 A6 E3 83 AB E3 83 80 E3 83 96 E3 83 A9 2E ; ウルダブラ.
00000020h: 65 6E 64 78 78 78 78 78 78 78 78 78 78 78 78 78 ; endxxxxxxxxxxxxx
00000030h: 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 ; xxxxxxxxxxxxxxxx

程序输出:

encoding = System.Text.UTF8Encoding

encoding = System.Text.UTF8Encoding

子字符串长度= 35

子串=从殲c´ƒ»一ƒ€,¦ƒ«一ƒ€ƒ——ƒ©.endxxxxxxxxxxxxxxxxxx

encoding = System.Text.UTF8Encoding

而我想让它输出:

encoding = System.Text.UTF8Encoding

encoding = System.Text.UTF8Encoding

子字符串长度= 35

子串=从殲c´ƒ»一ƒ€,¦ƒ«一ƒ€ƒ——ƒ©指标

最终

encoding = System.Text.UTF8Encoding

所以我的问题是为什么substring.Length返回35,但substring似乎包含>35个字符呢?我是否错误地使用了String.Substring ?还是与StreamReader有关?还是别的什么?

c# StreamReader或String读取的字符比要求的多

StreamReader正在正确读取,Substring恰好产生35个字符。

点是系统。控制台-令人毛骨悚然的微软产品-无法显示Unicode字符。

您可以通过在gui应用程序中运行相同的代码来验证这一点。在MessageBox或Label中,您将获得所需的输出