C#读取文件添加特殊字符

C# Reading a file add special characters

我正在读取具有这种结构的文本文件:

20150218;"C7";"B895";00101;"FTBCCAL16"

我读了这行然后这样拆分:

System.IO.StreamReader fichero = new System.IO.StreamReader(ruta, Encoding.Default);
while ((linea = fichero.ReadLine()) != null)
{
    // Split by ";"
    String[] separador = linea.Split(';');
}

但是当我看到"linea"的内容时,我有这个:

"20150218";\"C7\";\"B895\";"00101";\"FTBCCAL16\"

如您所见,streamreader 在输出中添加了一些特殊字符,例如“”和\。我想得到这个

20150218;"C7";"B895";00101;"FTBCCAL16"

有办法获得吗? 提前致谢!问候!

您正在 Visual Studio 调试器中观看它,它只是以这种方式显示您的台词。您可以将结果写入控制台或文件。你会看到没有特殊字符的普通文本。

好的,这里引用自MSDN

At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string @"C:\files.txt" will appear in the watch window as "C:\files.txt".

在您的 " 情况下,它使用 \" (Verbatim 字符串),这在调试时可见。

为什么会这样?

双引号"是一个escape sequence

Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark (")

所以当一个字符串有目的地包含转义序列时,您需要将其表示为verbatim string。这就是编译器所做的,这就是你在调试器中看到的

StreamReader 根本没有添加或修改从文件中读取的字符串。

如果您在 Visual Studio 调试器中查看 separador 的内容,它将向任何特殊字符添加一个转义序列(用于显示目的)。

显示的格式与您在创建字符串常量时必须在代码编辑器中输入它们的方式相匹配。

例如,


然而,这些字符串(在内存中)的真实内容没有被转义。它们与您在问题中所期望的完全一样。

如果您输出它们或尝试在代码中操作它们,它们将具有正确的内容。


所以,你的代码是正确的。您只需要了解 escape sequences 以及字符串在 Visual Studio 调试器中的显示方式。


更新:

有关如何在调试器中显示不带引号的字符串的说明,请参阅 this question