VB.Net/File Directory/Text File Read
Содержание
Open Text file and count the lines
<source lang="vbnet"> Imports System Imports System.Drawing Imports System.Data Imports System.IO Imports System.Collections Imports System.Windows.Forms Imports System.Drawing.Printing Public Class MainClass
Shared Sub Main() Dim myReader As StreamReader Try myReader = File.OpenText("test.vb") Catch e As IOException Console.WriteLine(e.ToString) Console.WriteLine(e.Message) Exit Sub End Try Dim lineCounter As Integer = 0 Dim currentLine As String, currentData As String Do Try currentLine = myReader.ReadLine lineCounter = lineCounter + 1 Catch e As EndOfStreamException Console.WriteLine(e.Message) Finally currentData = currentData & currentLine & vbCrLf End Try Loop While currentLine <> Nothing Console.WriteLine("Number of lines read: " & lineCounter - 1 ) myReader.Close() myReader = Nothing End Sub
End Class
</source>
Read and Write Files
<source lang="vbnet"> Public Class MainClass
Public Shared Function ReadTextFromFile(ByVal Filename As String) As String Dim strFileText As String Dim MyReader As System.IO.StreamReader = System.IO.File.OpenText(Filename) strFileText = MyReader.ReadToEnd MyReader.Close() Return strFileText End Function Public Shared Sub WriteTextToFile(ByVal Filename As String, ByVal Text As String) Dim MyWriter As System.IO.StreamWriter = System.IO.File.CreateText(Filename) MyWriter.Write(Text) MyWriter.Close() End Sub Public Shared Sub Main WriteTextToFile("c:\b.txt", ReadTextFromFile("c:\a.txt")) End Sub
End Class
</source>
Read Text File Content
<source lang="vbnet"> Imports System.IO Module Module1
Sub Main() Dim TextFile As New StreamReader("test.txt") Dim Content As String Do Content = TextFile.ReadLine() If (Content <> Nothing) Then Console.WriteLine(Content) End If Loop While (Content <> Nothing) TextFile.Close() End Sub
End Module
</source>
Read Text File in a single Statement
<source lang="vbnet"> Imports System Imports System.Windows.Forms Imports System.IO Public Class MainClass
Shared Sub Main() Dim plainTextFileName As String = "test.txt"
Console.WriteLine( File.ReadAllText(plainTextFileName)) End Sub
End Class
</source>
Text File content output
<source lang="vbnet"> Imports System Imports System.IO Public Class MainClass
Shared Sub Main() Dim fileName As String fileName = "test.vb" Try Dim stream As StreamReader stream = New StreamReader(fileName) Console.WriteLine( stream.ReadToEnd() ) Catch exceptionCatch As IOException Console.WriteLine("FILE ERROR") End Try End Sub " Main
End Class
</source>