C#读、写txt文件

阅读更多
static void Main(string[] args) 
{ 
	string strLine; 
	try 
	{ 
		Console.Write("请输入文件路径及文件名:"); 
		string mess = Console.ReadLine(); 
		FileStream aFile = new FileStream(mess, FileMode.Open); 
		StreamReader sr = new StreamReader(aFile);//用FileStream对象实例化一个StreamReader对象 
		//strLine = sr.ReadToEnd();//读取完整的文件,如果用这个方法,就可以不用下面的while循环 
		strLine = sr.ReadLine();// 读取一行字符并返回 
		while (strLine != null) 
		{ 
			Console.WriteLine(strLine); 
			strLine = sr.ReadLine(); 
		} 
			sr.Close(); 
			Console.ReadLine(); 
	} 
	catch (IOException e) 
	{ 
		Console.WriteLine("an IOexception has been thrown!"); 
		Console.WriteLine(e.ToString()); 
		return; 
	} 
} 


//写操作
public void Write(string text)
{
    FileStream fs = new FileStream("D:\\A.txt",FileMode.Apend);
    StreamWriter sw = new StreamWriter(fs,Encoding.Default);
    sw.Write(text);
    sw.Close();
    fs.Close();
}

你可能感兴趣的:(C,C++,C#)