欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2021-06-29 08:27:43|栏目:.NET代码|点击:

读取文本文件中的内容

此示例读取文本文件的内容以使用 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();

上一篇:如何利用扩展方法来链式的对MVC 3中的页面进行验证

栏    目:.NET代码

下一篇:c# 死锁和活锁的发生及避免

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

本文地址:http://www.codeinn.net/misctech/149848.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有