c#读写txt

//读取txt
StreamReader sR1 = new StreamReader(@"g:\temp\a.txt"); 
// 同样也可以指定编码方式 
StreamReader sR2 = new StreamReader(@"g:\temp\a.txt", Encoding.UTF8);

FileStream fS = new FileStream(@"g:\temp\a.txt", FileMode.Open, FileAccess.Read, FileShare.None); 
StreamReader sR3 = new StreamReader(fS); 
StreamReader sR4 = new StreamReader(fS, Encoding.UTF8);


/ 读一行 
string nextLine = sR.ReadLine();

// 读一个字符 
int nextChar = sR.Read();

// 读100个字符 
int n = 100; 
char[] charArray = new char[n]; 
int nCharsRead = sR.Read(charArray, 0, n);  
    
// 全部读完 
string restOfStream = sR.ReadToEnd();

假如我们需要一行一行的读,将整个文本文件读完,下面看一个完整的例子:
StreamReader sR = File.OpenText(@"g:\temp\a.txt"); 
string nextLine; 
while ((nextLine = sR.ReadLine()) != null) 
{ 
    Console.WriteLine(nextLine); 
} 
sR.Close(); 

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

//如果你有一个字符串数组,你要把数组的每一个元素作为一行写入文件中,可以用File.WriteAllLines方法
string[] strs = { "Good Morning!","Good Afternoon!","Good Evening!"}; 
File.WriteAllLines(@"c:\temp\a.txt", strs); 
// 也可以指定编码方式 
File.WriteAllLines(@"c:\temp\a.txt", strs, Encoding.ASCII);

//使用File.WriteAllText或File.WriteAllLines方法时,如果指定的文件路径不存在,会创建一个新文件;如果文件已经存在,则会覆盖原文件



// 如果文件不存在,创建文件; 如果存在,覆盖文件 
StreamWriter sW1 = new StreamWriter(@"c:\temp\a.txt"); 

// 也可以指定编码方式, true 是 Appendtext, false 为覆盖原文件 
StreamWriter sW2 = new StreamWriter(@"c:\temp\a.txt", true, Encoding.UTF8);

// FileMode.CreateNew: 如果文件不存在,创建文件;如果文件已经存在,抛出异常 
FileStream fS = new FileStream(@"C:\temp\a.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read); 
StreamWriter sW3 = new StreamWriter(fS); 
StreamWriter sW4 = new StreamWriter(fS, Encoding.UTF8);

// 如果文件不存在,创建文件; 如果存在,覆盖文件 
FileInfo myFile = new FileInfo(@"C:\temp\a.txt"); 
StreamWriter sW5 = myFile.CreateText(); 

// 写一个字符            
sw.Write('a');

// 写一个字符数组 
char[] charArray = new char[100]; 
sw.Write(charArray);

// 写一个字符数组的一部分(10~15)
sw.Write(charArray, 10, 15); 

//同样,StreamWriter对象使用完后,不要忘记关闭。sW.Close(); 最后来看一个完整的使用StreamWriter一次写入一行的例子:
FileInfo myFile = new FileInfo(@"C:\temp\a.txt"); 
StreamWriter sW = myFile.CreateText();
string[] strs = { "早上好", "下午好" ,"晚上好};            
foreach (var s in strs) 
{ 
    sW.WriteLine(s); 
} 
sW.Close(); 

猜你喜欢

转载自blog.csdn.net/weixin_44825442/article/details/88858954