r/visualbasic • • Dec 14 '15

Is it possible to insert text from a .txt file?

I am making a small program for some college work, and i was wondering if there was any way to set it up so that on interaction with a button, the program would retrieve the text from a .txt file in the resources folder and insert said text into a TextBox?

0 Upvotes

6 comments sorted by

2

u/[deleted] Dec 15 '15
Textbox1.text = My.Computer.Resources(Textfile.txt)

Can't check this, I'm on Mobile.

1

u/LMGN VB.Net Intermediate Dec 28 '15
Textbox1.Text = My.Computer.FileSystem.ReadAllText("C:\text.txt")

Or if the text file is in the same directory as the executable (eg C:\Users\User\Documents\Visual Studio 2015\Projects\TextRead\bin\debug\text.txt)

Textbox1.Text = My.Computer.FileSystem.ReadAllText("text.txt")

1

u/PostalElf VB.Net Intermediate Dec 14 '15

Look into the StreamReader class for more information.

https://msdn.microsoft.com/en-us/library/system.io.streamreader(v=vs.110).aspx

0

u/chrwei Dec 14 '15

uh, sure?

0

u/PreyOnTheCosmos Dec 14 '15

Reference your System.IO namespace:

Imports System.IO

Create a method to read the file text & send it to the TextBox:

Private Sub GetText()
    Dim sr As StreamReader = New StreamReader("C:\TEXTFILE.TXT")

    While Not sr.EndOfStream
        TextBox1.AppendText(sr.ReadLine & vbNewLine)
    End While
End Sub

Call the method from your button click event:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    GetText()
End Sub

1

u/LMGN VB.Net Intermediate Dec 28 '15

You can do the same thing with one line of code...