A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小笨 中级黑马   /  2014-8-6 10:42  /  847 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 小笨 于 2014-8-6 10:53 编辑

在做入学考试测试题的时候,有个问题不会,是怎样从文本文档txt中读取文本?

4 个回复

倒序浏览
可以用StreamReader
回复 使用道具 举报
要用到文件操作,File.ReadAllLines(path); path是路径,从文本里面读取所有行,返回一个string 数组。
不懂可以查MSDN,转一个来自MSDN的例子。
  1. using System;
  2. using System.IO;
  3. class Test
  4. {
  5.     public static void Main()
  6.     {
  7.         string path = @"c:\temp\MyTest.txt";

  8.         // This text is added only once to the file.
  9.         if (!File.Exists(path))
  10.         {
  11.             // Create a file to write to.
  12.             string[] createText = { "Hello", "And", "Welcome" };
  13.             File.WriteAllLines(path, createText);
  14.         }

  15.         // This text is always added, making the file longer over time
  16.         // if it is not deleted.
  17.         string appendText = "This is extra text" + Environment.NewLine;
  18.         File.AppendAllText(path, appendText);

  19.         // Open the file to read from.
  20.         string[] readText = File.ReadAllLines(path);
  21.         foreach (string s in readText)
  22.         {
  23.             Console.WriteLine(s);
  24.         }
  25.     }
  26. }
复制代码
回复 使用道具 举报
_xixi_ 发表于 2014-8-6 10:48
要用到文件操作,File.ReadAllLines(path); path是路径,从文本里面读取所有行,返回一个string 数组。
不 ...

嗯,谢谢了!
回复 使用道具 举报
进来学习学习
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马