开发者

difference of reading files

string value1 = File.ReadAllText("C:\\file.txt");
string value2 = File.ReadAllText(@"C:\file.txt");

In the above statements when is the difference of using @"C:\file开发者_运维知识库.txt" and C:\file.txt


Compiler would read @"C:\file.txt" as is. Removing verbatim (@) will make it treat '\f' as a single escape character (Form feed). In other words:

@"C:\file.txt" == "C:\\file.txt"
@"C:\file.txt" != "C:\file.txt" // treated as C: + FormFeed + ile.txt

Verbatim string literals start with @ and are also enclosed in double quotation marks. For example:

@"good morning"  // a string literal

The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:

@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"

String literals:

A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.


When using a \ in a string, you normally have to use \\ because the \ is an escape character. In reality, the first string you show (File.ReadAllText("C:\file.txt");) should throw a compile error.

The @ will allow you to build your string without using \\ every time you need a \.


string value1 = "C:\file.txt";
string value2 = @"C:\file.txt";

the string for value1 will contain a formfeed character where the \f is, while the second one will keep the backslash and the f. (This becomes very clear if you try to output them in a console application with Console.Write...)

The correct way for the value1 version would be "C:\\file.txt"

(The value2 version uses whats called, as Dmitry said, a verbatim string)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜