天天看点

C#读写txt文件内容

//读取1:

StreamReader sR = File.OpenText(@"C:\temp\a.txt"); 
string nextLine; 
while ((nextLine = sR.ReadLine()) != null) 
{ 
    Console.WriteLine(nextLine); 
} 
sR.Close(); 

//读取2:
FileStream file = new FileStream("C:\\Users\\54301\\Desktop\\test.txt", FileMode.Open);
 StreamReader sr = new StreamReader(file);
string strstr = sr.ReadToEnd();

file.close();

sr.close();

///
//写入1:

string locatPath = “aaa.txt";
 using (StreamWriter sr = new StreamWriter(locatPath))
{
          sr.Write("");
}



//写入2:

string str1 = "Good Morning!"; 
File.WriteAllText(@"c:\temp\test\a.txt", str1); 
// 也可以指定编码方式 
File.WriteAllText(@"c:\temp\test\a.txt", str1, Encoding.ASCII); 
           
c#