Tuesday, August 4, 2015
Write in exist text files vb.net
Write in exist text files VB.net
Today I will teach you how to write in text files (.txt) using VB.Net. Let´s go :D
How to create a project in Visual Studio?
Exists many ways to create a new project in VS. For example, when you open your VS program, in the Start Page you will see the option New Project ...
If you can´t see the Start Page you can also click in File > New Project > Select Visual Basic > Windows Forms Application
Rename your project name if you want and click OK.
It´s easy!
Start in the Form
In the form, add a TextBox (or richtextbox) to place the text from the file. The textbox should supportMultiLine. You can enable it in the Properties of the textbox or using code like I will show in the example. Center it in the form. Also we need a Button.
The code …
Press Control + Alt + 0 to open the code page.
Click in combobox that is in the top, left side. Select FormX(events) and in the Combobox in the top right side select Load. This will generate the Load Event of the Form
Write the next lines of code:
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles Me.Load
Button1.Text = "Save”
TextBox1.Multiline = True
End Sub
Now do the same to the button. Select in the left Button1 and in the right side Click or more simple do double-click in the button in the designer.
Write this:
Private Sub Button1_Click(sender As Object, e As EventArgs) HandlesButton1.Click
If System.IO.File.Exists("C:\Test\About.inf") Then 'check if file exists' 'If yes the write in file
Try
Dim objwriter As New System.IO.StreamWriter("C:\Test\About.inf")
objwriter.Write(TextBox1.Text)
objwriter.Close()
MsgBox("File saved", vbInformation + vbOKOnly)
Catch ex As Exception
MsgBox(ex.Message, vbCritical + vbOKOnly, "Error")
End Try
End If
End Sub
The System.IO.StreamWriter, does not work only in .txt files, but also in other tipes like .inf or .ini and others. If the file is supported by the Notepad of Windows it will also open if you use my this method. Is important use the Try ... Catch ... End Try because if the file that you want to read is being used by other process you app will crash. And also, if the System.IO.StreamWriter doesn´t support that file.
Labels:
VB.net
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment