您的位置:首页 > 编程语言 > C#

C#读取txt文本文件的几种方式

2014-04-26 00:50 645 查看
1.按行读取:每次读取一行内容,即遇到回车键才会停止。

public void readfile(string filepath)

{

if (!File.Exists(filepath))

{

MessageBox.Show(" file not exits !");

return;

}

string[] result ;

FileStream fs = new FileStream(filepath, FileMode.Open);

using (StreamReader sr = new StreamReader(fs, Encoding.Default))

{

List<string> list = new List<string>();

string input;

while (!sr.EndOfStream)

{

input= sr.ReadLine().ToString();



}

}



sr.Close();

}

2. 理论上任意形式的读取方式

using System;

public class SplitTest {
    public static void Main() {

        string words = "This is a list of words, with: a bit of punctuation" +
                       "\tand a tab character.";

        string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

        foreach (string s in split) {

            if (s.Trim() != "")
                Console.WriteLine(s);
        }
    }
}
// The example displays the following output to the console:
//       This
//       is
//       a
//       list
//       of
//       words
//       with
//       a
//       bit
//       of
//       punctuation
//       and
//       a
//       tab
//       character
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: