网上找了一个读取文件的类,不会调用.麻烦帮下忙?谢了!随便举几个例子就好拉!
我主要看是如何调用这个类的啊.谢谢大家
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;namespace WindowsApplication46
{
class FileRead
{
static void main(string[]args)
{
FileRead fr = new FileRead();
fr.ReadData();
}
public void ReadData()
{
FileStream fs = new FileStream("NII.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);//创建filestream对象,告诉文件哪里,以及对文件内容采取的处理方式
StreamReader sr = new StreamReader(fs, Encoding.Unicode);//仅仅对文本内容进行读写
sr.BaseStream.Seek(0, SeekOrigin.Begin);//读一下看文件有没有内容,为下一步循环提出依据
string str = sr.ReadLine();
while (str != null)//如果文件有内容
{
Console.WriteLine("{0}", str);
//这里我的理解是 当输出一行后,指针移动到下一行~
str = sr.ReadLine();//读取
}
sr.Close();
fs.Close();
}
}
}
我主要看是如何调用这个类的啊.谢谢大家
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;namespace WindowsApplication46
{
class FileRead
{
static void main(string[]args)
{
FileRead fr = new FileRead();
fr.ReadData();
}
public void ReadData()
{
FileStream fs = new FileStream("NII.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);//创建filestream对象,告诉文件哪里,以及对文件内容采取的处理方式
StreamReader sr = new StreamReader(fs, Encoding.Unicode);//仅仅对文本内容进行读写
sr.BaseStream.Seek(0, SeekOrigin.Begin);//读一下看文件有没有内容,为下一步循环提出依据
string str = sr.ReadLine();
while (str != null)//如果文件有内容
{
Console.WriteLine("{0}", str);
//这里我的理解是 当输出一行后,指针移动到下一行~
str = sr.ReadLine();//读取
}
sr.Close();
fs.Close();
}
}
}
using System.IO;class Test
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
刚从msdn上找了个,楼主帮忙.举个例子给我看下
里面包含这main函数
要把里面的读文件的功能提出来放到单独的一个类里面
如果不能运行,请将 main 修改为 Main.
如果文件中有中文,(比如记事本创建的),请将 Encoding.Unicode 修改为 Encoding.Default
如果你想观看结果,请在最后加一句 Console.ReadKey(); 即可.代码你直接copy过去应该就能运行的.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;namespace WindowsApplication46
{
class FileRead
{
static void Main(string[] args)
{
FileRead fr = new FileRead();
fr.ReadData();
Console.ReadKey();
}
public void ReadData()
{
FileStream fs = new FileStream("NII.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);//创建filestream对象,告诉文件哪里,以及对文件内容采取的处理方式
StreamReader sr = new StreamReader(fs, Encoding.Default );//仅仅对文本内容进行读写
sr.BaseStream.Seek(0, SeekOrigin.Begin);//读一下看文件有没有内容,为下一步循环提出依据
string str = sr.ReadLine();
while (str != null)//如果文件有内容
{
Console.WriteLine("{0}", str);
//这里我的理解是 当输出一行后,指针移动到下一行~
str = sr.ReadLine();//读取
}
sr.Close();
fs.Close();
}
}
}