Any of the Words
Link to us
How to work with Text files
Click to e-mail author
Shows how to work with Text files.
Reading Text Files: the easiest way to open a text file is with the System.IO.File.OpenText() method. Code:'Dim your StreamReader Dim TextFileStream As System.IO.TextReader 'Load the textfile into the stream TextFileStream = System.IO.File.OpenText("C:\MyTextFile.txt") 'Read to the end of the file into a String variable. Dim MyFileContents As String = TextFileStream.ReadToEnd 'Close the Stream object TextFileStream.Close() The above code will open a text file on your C drive called MyTextFile.txt. It will load all of the text into a string variable called MyFileContents. It won't create a file of that name if it doesn't already exist (and will throw an exception which you should handle - but see later in the FAQ for how to create a new file). Creating Text Files: Code:'Dim your Text Writer Dim TW As System.IO.TextWriter 'Create a Text file and load it into the TextWriter TW = System.IO.File.CreateText("C:\MyTextFile.txt") 'Write a line TW.WriteLine("Hello World") 'Write another line TW.WriteLine("Hello World Again") 'Flush the text to the file TW.Flush() 'Close the File TW.Close() Append to an existing Text file: Code:'Dim your Stream Writer or Text Writer. Dim SW As IO.TextWriter 'Open a file for Appending SW = IO.File.AppendText("C:\MyTextFile.txt") 'Write a line to the bottom of the text file SW.WriteLine("This is another line added to the bottom of the text file.") 'Flush to the file SW.Flush() 'Close the object SW.Close() Here is how to get a random line from a text file with the smallest code I can think of. Extracting One Line From a File: Code:Dim RandomNumber As New Random() Dim Tr As IO.TextReader = System.IO.File.OpenText("C:\MyTextFile.txt") Dim FileLines() As String = Split(Tr.ReadToEnd(), vbCrLf) Tr.Close Dim MyRandomLine As String = FileLines(RandomNumber.Next(0, UBound(FileLines))) MsgBox(MyRandomLine) If you know what line you want to access then you can make it smaller like this : Code: Dim Tr As IO.TextReader = System.IO.File.OpenText("C:\MyTextFile.txt") Dim MyFileLine As String = Split(Tr.ReadToEnd(), vbCrLf)(3) Tr.Close MsgBox(MyFileLine) Note that the above code will return the fourth line from the file. It's zero based, so you would enter (0) for line 1, (1) for line 2 and so on. So, there's some easy and basic ways of getting text into and out of a text file in .Net. Try It !
© 2023 A1VBCode. All rights reserved.