c#怎么读文件!

来源:百度知道 编辑:UC知道 时间:2024/05/17 07:44:49
我的意思是 我用程序读一个TXT文本里面的内容。
把TXT中的文本框中的 每一行做为一个字符串保存到变量中!~~

using System.IO;
// ……………………
string[] a;
string path=@"";//文件路径
//然后:
a=File.ReadAllLines(path);

//或:(效果相似)

int sc=0;
a=new string[0xFF];
SR = File.OpenText(path);
string S;
S = SR.ReadLine();
while (S != null)
{
a[sc] = S;
sc++;
S = SR.ReadLine();
}
SR.Close();
//这时sc+1就是行数

string[] data = File.ReadAllLines("文件路径");

public void read()
{
Console.WriteLine("请输入文件名:");
string str = Console.ReadLine();
if(!File.Exists(str))
{
Console.WriteLine("没有此文件");
}
else
{
FileStream file = new FileStream(str,FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(file);
string s = sr.ReadLine();
while(s!=null)
{
Console.WriteLine(s);
s = sr.ReadLine();
}
sr.Close();