VB.Net Tutorial/Stream File/Text File Read — различия между версиями

Материал из VB Эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 12:56, 26 мая 2010

FileSystem.ReadAllText

public class Test
   public Shared Sub Main
        Console.WriteLine(My.ruputer.FileSystem.ReadAllText("test.txt"))
   End Sub
End class
Hello world!

Read text file content in Try Catch block

Imports System.IO
public class Test
   public Shared Sub Main
        Dim srReader As IO.StreamReader
        Dim strLine As String
        Dim blnDone As Boolean = False
        Dim strFileName As String = "test.txt"
        "Read text from a file and display it in a list box.
        srReader = New IO.StreamReader(strFileName)
        Try
            While Not blnDone
                strLine = srReader.ReadLine()
                If strLine Is Nothing Then
                    blnDone = True
                Else
                    Console.WriteLine(strLine)
                End If
            End While
            srReader.Close()
        Catch ex As Exception
            Console.WriteLine("An error has occurred.")
        End Try

   End Sub
End class
asdf

Read text file line by line

Public Class ReadFromFile
    Shared Sub Main()
    Dim sFileName As String
    Dim srFileReader As System.IO.StreamReader
    Dim sInputLine As String
        sFileName = "test.txt"
        srFileReader = System.IO.File.OpenText(sFileName)
        sInputLine = srFileReader.ReadLine()
        Do Until sInputLine is Nothing
            System.Console.WriteLine(sInputLine)
            sInputLine = srFileReader.ReadLine()
        Loop
    End Sub
End Class

Read text file to the file end

Imports System.IO

Public Class Tester
    Public Shared Sub Main
        Dim f As System.IO.FileStream
        Dim r As System.IO.StreamReader
        Dim mylength As Integer
        Dim i As Integer
        f = New System.IO.FileStream("test.txt", IO.FileMode.Open, IO.FileAccess.Read)
        r = New System.IO.StreamReader(f)
        Console.WriteLine(r.ReadToEnd())
        f.Close()
        r.Close()
    End Sub
End Class

Use StreamReader to read text file

Imports System.Text
Imports System.IO

Public Class Tester
    Public Shared Sub Main
        Dim myFileStream As FileStream
        Dim myStreamReader As StreamReader
        Dim intRead As Integer = 0
        Dim chrRead As Char = ""
        Dim strRead As String = ""
        Try
            myFileStream = New FileStream ("test.txt", FileMode.Open, FileAccess.Read)
            myStreamReader = New StreamReader(myFileStream)
            Do While intRead <> -1
                intRead = myStreamReader.Read()
                If intRead <> -1 Then chrRead = Convert.ToChar(intRead)
                strRead += chrRead
            Loop
            Console.WriteLine(strRead)
        Catch EX As IOException
            Console.WriteLine(EX.Message)
        End Try
    End Sub
End Class