简体   繁体   English

如何从C#中的文本文件读取数据?

[英]How to to read data from text file in c#?

I want to read data from text file I tried but it showing errors showing error at the path of the file 我想从我尝试过的文本文件中读取数据,但它显示错误,并在文件路径中显示错误

string txtfile = File.ReadAllText("D:\Temp\textdata.txt");
string txtdata = File.ReadAllText("D:\Temp\textstrings.txt");
string txtpara = File.ReadAllText("D:\Temp\textlines.txt");

Console.WriteLine(txtfile);
Console.WriteLine("\n");
Console.WriteLine("\n");
Console.WriteLine(txtpara);
Console.WriteLine("\n");
Console.WriteLine("\n");
Console.WriteLine("\n");
Console.WriteLine(txtdata);

My file is saved in d:\\temp\\textdata.txt 我的文件保存在d:\\temp\\textdata.txt

Can anyone tell me ? 谁能告诉我?

The problem is backslash symbol in your string containing filename. 问题是包含文件名的字符串中的反斜杠符号。 Sequence of characters \\t means tabulation symbol. 字符序列\\t表示制表符。

You should either prepend your string with @ sign like 您应该在字符串前面加上@符号,例如

@"D:\Temp\textdata.txt"

or use double slashes like 或使用双斜杠

"D:\\Temp\\textdata.txt"
string value = File.ReadAllText(@"D:\temp\textdata.txt");

Console.WriteLine(value);

Note the ' @ ', this is an escape character for the extra back slash in your path. 注意“ @ ”,这是路径中多余的反斜杠的转义字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM