15.1 Path
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Public Class Class1
Sub TestPathType()
Console.WriteLine(Path.AltDirectorySeparatorChar) ' => /
Console.WriteLine(Path.DirectorySeparatorChar) ' => \
Console.WriteLine(Path.PathSeparator) ' => ;
Console.WriteLine(Path.VolumeSeparatorChar) ' => :
' Note: the actual output from following methods includes unprintable characters.
Console.WriteLine(Path.GetInvalidPathChars()) ' => <>|
Console.WriteLine(Path.GetInvalidFileNameChars()) ' => <>|:*?\/
Console.WriteLine(Path.GetTempPath)
' => C:\Documents and Settings\Francesco\Local Settings\Temp
Console.WriteLine(Path.GetTempFileName)
' => C:\Documents and Settings\Francesco\Local Settings\Temp\tmp1FC7.tmp
'从路径字符串中提取信息
Dim file As String = "C:\MyApp\Bin\MyApp.exe"
Console.WriteLine(Path.GetDirectoryName(file)) ' => C:\MyApp\Bin
Console.WriteLine(Path.GetFileName(file)) ' => MyApp.exe
Console.WriteLine(Path.GetExtension(file)) ' => .exe
Console.WriteLine(Path.GetFileNameWithoutExtension(file)) ' => MyApp
Console.WriteLine(Path.GetPathRoot(file)) ' => C:\
Console.WriteLine(Path.HasExtension(file)) ' => True
Console.WriteLine(Path.IsPathRooted(file)) ' => True
' Retrieve the Windows main directory (parent of Windows system directory)
Console.WriteLine(Path.GetDirectoryName(Environment.SystemDirectory))
' Next line assumes that current directory is C:\MyApp.
Console.WriteLine(Path.GetFullPath("MyApp.Exe")) ' => C:\MyApp\MyApp.Exe
Console.WriteLine(Path.ChangeExtension("MyApp.Exe", "dat")) ' => MyApp.dat
Console.WriteLine(Path.Combine("C:\MyApp", "MyApp.Dat")) ' => C:\MyApp\MyApp.Dat
'\..表示当前目录的上一级目录
Console.WriteLine(Path.GetFullPath("c:\public\..\private\filename"))
End Sub
End Class
15.2 Directory和File
15.2.1 列举目录和文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Public Class Class1
Sub DisplayDirTree(
ByVal dir As String,
ByVal showFiles As Boolean,
Optional ByVal level As Integer = 0
)
' Display the name of this directory with correct indentation.
Console.WriteLine(New String("-"c, level * 2) & dir)
Try
' Display all files in this directory with correct indentation.
If showFiles = True Then
For Each fname As String In Directory.GetFiles(dir)
Console.WriteLine(New String(" "c, level * 2 + 2) & fname)
Next
End If
' A recursive call for all the subdirectories in this directory
For Each subdir As String In Directory.GetDirectories(dir)
DisplayDirTree(subdir, showFiles, level + 1)
Next
Catch
' Do nothing if any error (presumably "Drive not ready").
End Try
End Sub
'显示系统中所有驱动器的目录树
Sub a()
For Each rootDir As String In Directory.GetLogicalDrives
DisplayDirTree(rootDir, True, 0)
Next
End Sub
' Display all the *.txt files in C:\DOCS.
Sub b()
For Each fname As String In Directory.GetFiles("c:\docs", "*.txt")
Console.WriteLine(fname)
Next
End Sub
' Display only read-only .txt files in the c:\docs folder.
Sub c()
For Each fname As String In Directory.GetFiles("c:\docs", "*.txt")
If CBool(File.GetAttributes(fname) And FileAttributes.ReadOnly) Then
Console.WriteLine(fname)
End If
Next
End Sub
'自动在子目录中搜索
Sub d()
For Each file As String In Directory.GetFiles(
"c:\windows", "*.dll", System.IO.SearchOption.AllDirectories)
Console.WriteLine(file)
Next
End Sub
End Class
15.2.2 管理目录和文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Module Module2
Sub a()
Dim currDir As String = Directory.GetCurrentDirectory
Directory.SetCurrentDirectory("c:\temp")
'''''''''''''
''''
'''''''''''''
Directory.SetCurrentDirectory(currDir)
End Sub
Sub b()
Directory.CreateDirectory("c:\myTemp\data")
End Sub
Sub c()
If File.Exists("c:\data.txt") Then
File.Move("c:\data.txt", "d:\data.txt")
End If
End Sub
Sub d()
Directory.Delete("c:\tempDir", True)
End Sub
' Display system and hidden files in C:\.
Sub e()
For Each fname As String In Directory.GetFiles("C:\")
Dim attr As FileAttributes = File.GetAttributes(fname)
' Display the file if marked as hidden or system (or both).
If CBool(attr And (FileAttributes.Hidden Or FileAttributes.System)) Then
Console.WriteLine(fname)
End If
Next
End Sub
Sub f()
File.Copy("c:\data.bin", "c:\backup\data.bin", True)
End Sub
Sub g()
File.Replace("c:\data.bin", "c:\newdata.bin", "c:\data.bak", True)
End Sub
End Module
15.3 DirectoryInfo和FileInfo
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Module Module3
Sub a()
' Create a DirectoryInfo object that points to C:\.
Dim diRoot As New DirectoryInfo("c:\")
' Create a FileInfo object that points to c:\autoexec.bat.
Dim fiAutoexec As New FileInfo("c:\autoexec.bat")
' List the directories in c:\.
For Each di As DirectoryInfo In diRoot.GetDirectories()
Console.WriteLine(di.Name)
Next
' List all the *.txt files in c:\.
For Each fi As FileInfo In diRoot.GetFiles("*.txt")
Console.WriteLine(fi.Name)
Next
' Show files and directories in one operation
For Each fsi As FileSystemInfo In diRoot.GetFileSystemInfos()
' Use the [dir] or [file] prefix.
Dim prefix As String = Nothing
If CBool(fsi.Attributes And FileAttributes.Directory) Then
prefix = "dir"
Else
prefix = "file"
End If
' Print type, name and creation date.
Console.WriteLine("[{0}] {1} ?{2}", prefix, fsi.Name, fsi.CreationTime)
Next
' List all empty files in c:\.
For Each fi As FileInfo In diRoot.GetFiles()
If fi.Length = 0 Then Console.WriteLine(fi.Name)
Next
End Sub
Sub b()
' List all empty files in c:\.
Dim fiDoc As New FileInfo("c:\temps\temp.txt")
For Each fi As FileInfo In fiDoc.Directory.GetFiles()
Console.WriteLine(fi.Name)
Next
End Sub
'创建c:\tempdocs\Reports子目录,然后将其删除
Sub c()
Dim diDocs As New DirectoryInfo("c:\tempdocs")
diDocs.CreateSubdirectory("Reports")
diDocs.Delete(True)
End Sub
' Encrypt all the writable files in the c:\private directory.
Sub d()
Dim diPrivate As New DirectoryInfo("c:\private")
For Each fi As FileInfo In diPrivate.GetFiles()
If Not fi.IsReadOnly Then fi.Encrypt()
Next
End Sub
End Module
15.4 DriveInfo
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Module Module4
' Display the volume label of drive C.
Sub a()
Dim driveC As New DriveInfo("c:")
Console.WriteLine("Label of C: drive: {0}", driveC.VolumeLabel)
End Sub
' Display name and total size of all available drives.
Sub b()
For Each di As DriveInfo In DriveInfo.GetDrives()
If di.IsReady Then
Console.WriteLine("Drive {0}: {1:N} bytes", di.Name, di.TotalSize)
End If
Next
End Sub
Sub c()
Dim driveD As New DriveInfo("d:")
driveD.VolumeLabel = "MyData"
End Sub
' Display information of all drives
Sub d()
Console.WriteLine("{0,-6}{1,-10}{2,-8}{3,-16}{4,18}{5,18}", "Name",
"Label", "Type", "Format", "TotalSize", "TotalFreeSpace")
Console.WriteLine(New String("-"c, 78))
For Each di As DriveInfo In DriveInfo.GetDrives()
If di.IsReady Then
Console.WriteLine(
"{0,-6}{1,-10}{2,-8}{3,-16}{4,18:N0}{5,18:N0}",
di.Name, di.VolumeLabel, di.DriveType.ToString, di.DriveFormat, di.TotalSize, di.TotalFreeSpace)
Else
Console.WriteLine("{0,-6}(not ready)", di.Name)
End If
Next
End Sub
End Module
15.7 Stream
15.7.1 流操作
15.7.2流式阅读器和流式编写器
15.7.3读取和写入文本文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Imports System.Text
Module Module5
Dim fileName As String = "c:\test.txt"
' With the File.OpenText static method
Sub a()
Dim sr As StreamReader = File.OpenText(fileName)
End Sub
' With the OpenText instance method of a FileInfo object
Sub a2()
Dim fi2 As New FileInfo(fileName)
Dim sr2 As StreamReader = fi2.OpenText
End Sub
' By passing a FileStream from the Open method of the File class to
' the StreamReader's constructor method
' (This technique lets you specify mode, access, and share mode.)
Sub a3()
Dim st3 As Stream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
Dim sr3 As New StreamReader(st3)
End Sub
' By opening a FileStream on the file and then passing it
' to the StreamReader's constructor method
Sub a4()
Dim fs4 As New FileStream(fileName, FileMode.Open)
Dim sr4 As New StreamReader(fs4)
End Sub
' By getting a FileStream from the OpenRead method of the File class
' and passing it to the StreamReader's constructor
Sub a5()
Dim sr5 As New StreamReader(File.OpenRead(fileName))
End Sub
' By passing the filename to the StreamReader's constructor
Sub a6()
Dim sr6 As New StreamReader(fileName)
End Sub
' By passing the filename and encoding
Sub a7()
Dim sr7 As New StreamReader("c:\autoexec.bat", System.Text.Encoding.Unicode)
Dim sr8 As New StreamReader(fileName, System.Text.Encoding.ASCII)
End Sub
' As before, but we let the system decide the best encoding.
Sub a8()
Dim sr9 As New StreamReader(fileName, True)
End Sub
' Create a file for sequential reading and writing, with a 2K buffer;
' The file will be deleted when closed.
Sub b()
Dim fs10 As New FileStream("c:\tryme.tmp",
FileMode.CreateNew,
FileAccess.ReadWrite,
FileShare.Read,
2048,
FileOptions.SequentialScan Or FileOptions.DeleteOnClose)
End Sub
' Display all the text lines in the c:\test.txt file.
Sub c()
Dim sr As New StreamReader(fileName)
Do Until sr.Peek = -1
Console.WriteLine(sr.ReadLine())
Loop
sr.Close()
End Sub
Sub d()
Using sr As New StreamReader(fileName)
Do Until sr.EndOfStream
Console.WriteLine(sr.ReadLine())
Loop
End Using
End Sub
Sub e()
' Read the entire contents of C:\test.doc in one shot.
Dim sr As New StreamReader(fileName)
Dim fileContents As String = sr.ReadToEnd()
' If the file is longer than 100 chars, process it again, one character at a
' time (admittedly a silly thing to do, but it's just a demo).
If fileContents.Length >= 100 Then
' Reset the stream's pointer to the beginning.
sr.BaseStream.Seek(0, SeekOrigin.Begin)
' Read individual characters until EOF is reached.
Do Until sr.EndOfStream
' Read method returns an integer, so convert it to Char.
Console.Write(sr.Read().ToString())
Loop
End If
sr.Close()
End Sub
Sub f()
' By means of the CreateText static method of the File type
Dim fileName As String = "c:\text.dat"
Dim sw1 As StreamWriter = File.CreateText(fileName)
' By passing a FileStream from the Open method of the File class to
' the StreamWriter's constructor method
Dim st2 As Stream = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)
Dim sw2 As New StreamWriter(st2)
' By opening a FileStream on the file and then passing it
' to the StreamWriter's constructor
Dim fs3 As New FileStream(fileName, FileMode.Open)
Dim sw3 As New StreamWriter(fs3)
' By getting a FileStream from the OpenWrite method of the File type
' and passing it to the StreamWriter's constructor
Dim sw4 As New StreamWriter(File.OpenWrite(fileName))
' By passing the filename to the StreamWriter's constructor
Dim sw5 As New StreamWriter(fileName)
' Open the c:\test.dat file in append mode, be prepared to output
' ASCII characters, and use a 2K buffer.
Dim sw6 As New StreamWriter("c:\test.new", True, Encoding.ASCII, 2024)
' Terminate each line with a null character followed by a newline character.
sw6.NewLine = ControlChars.NullChar & ControlChars.NewLine
End Sub
' This actually writes data to the file and closes it.
Sub g()
Using sr As New StreamReader("c:\test.txt")
Using sw As New StreamWriter("c:\test.new")
Do Until sr.EndOfStream
sw.WriteLine(sr.ReadLine.ToUpper())
Loop
End Using
End Using
End Sub
'使用内存获得更好的性能
Sub h()
Using sr As New StreamReader("c:\test.txt"), sw As New StreamWriter("c:\test.new")
sw.WriteLine(sr.ReadToEnd().ToUpper())
End Using
End Sub
End Module
15.7.4 读取和写入二进制文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Module Module6
Dim fileName As String = "c:\values.dat"
Sub a()
' Associate a stream with a new file opened with write access.
Dim st As Stream = File.Open(fileName, FileMode.Create, FileAccess.Write)
' Create a BinaryWriter associated with the output stream.
Dim bw As New BinaryWriter(st)
' Save 10 Double values to the file.
Dim rand As New Random()
For i As Integer = 1 To 10
bw.Write(rand.NextDouble())
Next
' Flush the output data to the file.
bw.Close()
End Sub
' Read back values written in previous code.
Sub b()
' Associate a stream with an existing file, opened with read access.
Dim st2 As Stream = File.Open(fileName, FileMode.Open, FileAccess.Read)
' Create a BinaryReader associated with the input stream.
Using br2 As New BinaryReader(st2)
' Loop until data is available.
Do Until br2.PeekChar() = -1
' Read the next element. (We know it's a Double.)
Console.WriteLine(br2.ReadDouble())
Loop
' Next statement closes both the BinaryReader and the underlying stream.
End Using
End Sub
End Module
15.7.5 处理定长和分隔数据文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports Microsoft.VisualBasic.FileIO
Imports System.Text
Module Module7
'分界符文件
Sub ReadDelimitedFiles()
Dim fileName As String = "data.txt"
Dim parser As New TextFieldParser(fileName, Encoding.Default)
' Field separator can be either a comma or a semicolon.
parser.Delimiters = New String() {",", ";"}
parser.TrimWhiteSpace = True
Do Until parser.EndOfData
Dim fields() As String = parser.ReadFields()
' Process each field in current record here.
Console.WriteLine("First={0}, Last={1}, City={2}", fields(0), fields(1), fields(2))
Loop
parser.Close()
End Sub
'固定宽度文件
Sub ReadFixedLengthFiles()
Using parser As New TextFieldParser("data2.txt", Encoding.Default)
parser.TextFieldType = FieldType.FixedWidth
parser.FieldWidths = New Integer() {8, 10, 6}
Do Until parser.EndOfData
Dim fields() As String = parser.ReadFields()
Console.WriteLine("First={0}, Last={1}, City={2}", fields(0), fields(1), fields(2))
Loop
End Using
End Sub
'记录字段不一样
Sub ReadTextFilesWithHeaders()
Using parser As New TextFieldParser("data3.txt", Encoding.Default)
parser.TextFieldType = FieldType.FixedWidth
Dim headerWidths() As Integer = {3, 4, 11, 12}
Dim detailWidths() As Integer = {3, 6, 18, 6}
parser.FieldWidths = headerWidths
Do Until parser.EndOfData
Dim code As String = parser.PeekChars(2)
If code = "IH" Then
parser.FieldWidths = headerWidths
Dim fields() As String = parser.ReadFields()
Console.WriteLine("Invoice #{0}, Date={1}, Customer={2}", fields(1), fields(2), fields(3))
ElseIf code = "ID" Then
parser.FieldWidths = detailWidths
Dim fields() As String = parser.ReadFields()
Console.WriteLine(" #{0} {1} at ${2} each", fields(1), fields(2), fields(3))
Else
Throw New MalformedLineException("Invalid record code")
End If
Loop
End Using
End Sub
End Module
15.8 其他Stream类型
15.8.1 内存流
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Imports System.Text
Imports System.Globalization
Module Module8
Sub TestMemoryStream()
' Create a memory stream with initial capacity of 1 KB.
Dim st As New MemoryStream(1024)
Dim bw As New BinaryWriter(st)
Dim rand As New Random()
' Write 10 random Double values to the stream.
For i As Integer = 1 To 10
bw.Write(rand.NextDouble())
Next
' Rewind the stream to the beginning and read back the data.
st.Seek(0, SeekOrigin.Begin)
Dim br As New BinaryReader(st)
Do Until br.PeekChar = -1
Console.WriteLine(br.ReadDouble())
Loop
bw.Close()
br.Close()
st.Close()
End Sub
Sub ReadWriteStrings()
Dim st As New MemoryStream(1000)
Dim bw As New BinaryWriter(st)
' The BinaryWriter.Write method outputs a length-prefixed string.
bw.Write("a length-prefixed string")
' We'll use this 1-KB buffer for both reading and writing.
Dim buffer(1023) As Char
Dim s As String = "13 Characters" ' A fixed-length string
s.CopyTo(0, buffer, 0, s.Length) ' Copy into the buffer.
bw.Write(buffer, 0, s.Length) ' Output first 13 chars in buffer.
bw.Write(buffer, 0, s.Length) ' Do it a second time.
' Rewind the stream, and prepare to read from it.
st.Seek(0, SeekOrigin.Begin)
Dim br As New BinaryReader(st)
' Reading the length-prefixed string is simple.
Console.WriteLine(br.ReadString()) ' => a length-prefixed string
' Read the fixed-length string (13 characters) into the buffer.
br.Read(buffer, 0, 13)
s = New String(buffer, 0, 13) ' Convert to a string.
Console.WriteLine(s) ' => 13 Characters
' Another way to read a fixed-length string (13 characters)
' (ReadChars returns a Char array that we can pass to the string constructor.)
s = New String(br.ReadChars(13))
Console.WriteLine(s) ' => 13 Characters
End Sub
End Module
15.8.2 基于字符串的流
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Imports System.IO
Imports System.Text
Imports System.Globalization
Module Module9
'ReadLine
Sub a()
Dim veryLongString As String = ""
Dim strReader As New StreamReader(veryLongString)
Do Until strReader.Peek = -1
Console.WriteLine(strReader.ReadLine)
Loop
End Sub
Sub StringWriterType()
' Create a string with the space-separated abbreviated names of weekdays.
Dim sb As New StringBuilder()
' The StringWriter associated with the StringBuilder
Dim strWriter As New StringWriter(sb)
' Output day names to the string.
For Each d As String In DateTimeFormatInfo.CurrentInfo.AbbreviatedDayNames
strWriter.Write(d)
strWriter.Write(" ") ' Append a space.
Next
Console.WriteLine(sb) ' => Sun Mon Tue Wed Thu Fri Sat
End Sub
End Module