欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Windows系统中使用C#读取文本文件内容的小示例

程序员文章站 2022-06-03 15:21:03
读取文本文件中的内容 此示例读取文本文件的内容以使用 system.io.file 选件类的静态方法 readalltext 和 readalllines。 c...

读取文本文件中的内容

此示例读取文本文件的内容以使用 system.io.file 选件类的静态方法 readalltext 和 readalllines。

class readfromfile
{
  static void main()
  {
    // the files used in this example are created in the topic
    // how to: write to a text file. you can change the path and
    // file name to substitute text files of your own.

    // example #1
    // read the file as one string.
    string text = system.io.file.readalltext(@"c:\users\public\testfolder\writetext.txt");

    // display the file contents to the console. variable text is a string.
    system.console.writeline("contents of writetext.txt = {0}", text);

    // example #2
    // read each line of the file into a string array. each element
    // of the array is one line of the file.
    string[] lines = system.io.file.readalllines(@"c:\users\public\testfolder\writelines2.txt");

    // display the file contents by using a foreach loop.
    system.console.writeline("contents of writelines2.txt = ");
    foreach (string line in lines)
    {
      // use a tab to indent each line of the file.
      console.writeline("\t" + line);
    }

    // keep the console window open in debug mode.
    console.writeline("press any key to exit.");
    system.console.readkey();
  }
}

一次一行地读取文本文件
本示例使用 streamreader 类的 readline 方法将文本文件的内容读取(一次读取一行)到字符串中。所有文本行都保存在字符串 line 中并显示在屏幕上。

int counter = 0;
string line;

// read the file and display it line by line.
system.io.streamreader file = 
  new system.io.streamreader(@"c:\test.txt");
while((line = file.readline()) != null)
{
  system.console.writeline (line);
  counter++;
}

file.close();
system.console.writeline("there were {0} lines.", counter);
// suspend the screen.
system.console.readline();