Visual Basic 2019, handling text files
A quick tutorial on how to read and write to textfiles.
Reading an entire text file to a string :
To open the entire contents of a text file and place it in a string use the following line of code :
"String" = My.Computer.FileSystem.ReadAllText("Text file")
"String" is the string you wish to store the contents of the text file in.
"Text file" is the path and file name of the text file you wish to open.
Example :
Dim MyString as String
MyString = My.Computer.FileSystem.ReadAllText("C:\MyTextFile.txt")
This will open a text file with the name of MyTestFile.txt and store it's contents in a string called MyString.
Reading a text file line by line to a string :
Work in progress...
sFilename = "C:\Listview.txt"
If Dir(sFilename.ToString) <> "" Then
sFileReader = System.IO.File.OpenText(sFilename)
sInputLine = sFileReader.ReadLine()
Do Until sInputLine Is Nothing
sInputLine = sFileReader.ReadLine()
Loop
End If
Work in progress...
Writing to contents of a string to a text file :
To write the contents of a string to a text file use the following line of code :
My.Computer.FileSystem.WriteAllText("Text file", "String", "False")
"Text file" is the path and file name of the text file you wish to write to.
"String" is the string you wish to write to the text file to.
"False" is for if you wish to append to the file or overwright the file. True is to append or False is to overwrite.
Example :
Dim MyString as String = "Hello World!!!"
My.Computer.FileSystem.WriteAllText("C:\MyTextFile.txt", MyString, False)
This example will create or overwrite the contents of the file MyTextFile.txt with the contents of MyString.
Dim MyString as String = "Hello World!!!"
My.Computer.FileSystem.WriteAllText("C:\MyTextFile.txt", MyString, True)
This example will append the contents of MyString to the end of the MyTextFile.txt file.
Creating a directory :
To create a directory use the following line of code :
My.Computer.FileSystem.CreateDirectory("Directory")
"Directory" is then path of the directory you want created.
Example :
My.Computer.FileSystem.CreateDirectory("C:\MyDirectory")
This example will create a directory called MyDirectory on your C drive.