文件读写整理:
1.文件读操作:
类System.IO.StreamReader,实现一个TextReader对象,用法如下:
DimstrLine As String
Dim ReadStreamAs New System.IO.StreamReader("F:\Materials\SmartPhoneGames\code\Classes\AboutCoderLayer.cpp")
If ReadStream IsNot Nothing Then
Do Until ReadStream.EndOfStream
strLine = ReadStream.ReadLine()
………
Loop
ReadStream.Close()
End If
2.文件写操作:
类System.IO.StreamWriter ,实现一个TextWriter对象,用法如下:
Dim WriteStreamAs StreamWriter = File.CreateText("D:\errInfo.txt" )
DimcurrDateTimeAs String = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
WriteStream.WriteLine(currDateTime)
WriteStream.Close()
3.文件的其他操作:
类System.IO.File,提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建 FileStream 对象。举例如下:
(1)File.CreateText("D:\errInfo.txt" ),创建或打开一个文件用于写入 UTF-8 编码的文本。
(2)FileStream fs = File.Create(@"c:\temp\MyTest.txt")
(3)File.Copy(string sourceFileName,string destFileName,booloverwrite) 用法举例:
string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
}
catch()
{
……
}
(4)File.Delete(pathAsstring ),用法如下:
File.Delete("F:\VBNETWorkSpace\TestFiles\AppDelegate.cpp")
(5)File.Move(sourceFileName As String, destFileName As String),用法如下:
Private Sub FileMove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FileMove.Click
Dim path As String = "c:\temp\MyTest.txt"
Dim path2 As String = "c:\temp2\MyTest2.txt"
Try
If File.Exists(path) = False Then
Dim fs As FileStream = File.Create(path)
fs.Close()
End If
If File.Exists(path2) Then
File.Delete(path2)
End If
File.Move(path, path2)
Catch ex As Exception
End Try
End Sub