上QQ阅读APP看书,第一时间看更新
3.2 文本文件的读写
System.IO命名空间下,FileStream和StreamReader是处理文本文件的。
1 public void文本文件的读写() 2 { //using System.IO 3 string path = @"F:\VSTO\a.txt"; 4 FileStream fs = new FileStream(path, FileMode.Create); 5 StreamWriter sw = new StreamWriter(fs); 6 //开始写入 7 sw.WriteLine("Hello VSTO"); 8 sw.WriteLine("Second Line"); 9 sw.WriteLine("3th Line"); 10 //清空缓冲区 11 sw.Flush(); 12 //关闭流 13 sw.Close(); 14 fs.Close(); 15 //读入内容 16 StreamReader sr = new StreamReader(path, Encoding.Default); 17 String line; 18 result = ""; 19 while ((line = sr.ReadLine()) ! = null) 20 { 21 result += line + "\n"; 22 } 23 }
代码中创建了一个a.txt文本文件,写入内容后关闭文件。代码中第16行利用sr这个对象读取文本文件的每一行内容,把每次读取的内容赋给变量line。
与此对应的VBA代码如下:
1 Public Sub文本文件的读写() 2 '引用Scripting runtime 3 Dim FSO As New Scripting.FileSystemObject 4 Dim path As String 5 path = "E:\VBA\RegExp\百家姓.txt" 6 Dim fs As TextStream 7 Set fs = FSO.CreateTextFile(path, True, False) 8 '开始写入 9 fs.WriteLine ("Hello VSTO") 10 fs.WriteLine ("Second Line") 11 fs.WriteLine ("3th Line") 12 fs.Close 13 '读入内容 14 Set fs = FSO.OpenTextFile(path, ForReading, True) 15 result = "" 16 While fs.AtEndOfStream = False 17 result = result & fs.ReadLine & vbNewLine 18 Wend 19 '如果一次性读取全部内容,使用: result = fs.ReadAll替换上述While循环体 20 fs.Close 21 End Sub