且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#读取文本文件

更新时间:2023-02-20 11:05:09

读取单个元素



解决方案取决于您要对文本执行的操作。您可以逐行读取文件并从行中提取特定关键字,或者您可以从文件读取整个文本到变量并解析它。

如果文件是大文本,更好的解决方案将被读取但是正如我所说,这取决于你的要求。



阅读文本文件很简单:

Hi,

Solution depends on that what you want to do with text. You can read file line by line and extract specific keyword from line or you can read entire text from file to a variable and them parse it.
If file is large text, better solution will be read line by line, but as i said, it depends on your demands.

Reading text files is simple:
using (var streamReader = new StreamReader(@"C:\file.txt"))
{
    // You can read line by line
    while (!streamReader.EndOfStream)
    {
        var line = streamReader.ReadLine();
        // Do something with readed line
    }
    // OR read entire text and assign to variable
    var allText = streamReader.ReadToEnd();
}





希望它可以帮到你。



Hope it helps you.


使用这个对象,

IO.File [ ^ ]

http://support.microsoft.com/kb/304430/EN-US [ ^ ]

http://www.tutorialspoint.com/csharp/csharp_file_io.htm [ ^ ]



-KR
Use this object,
IO.File[^]
http://support.microsoft.com/kb/304430/EN-US[^]
http://www.tutorialspoint.com/csharp/csharp_file_io.htm[^]

-KR