Pressing a button in visual basic - vb.net

I am new to Visual Basic.NET and I am just playing around with it. I have a book that tells me how to read from a file but not how to write to the file with a button click. All I have is a button and a textbox named fullNameBox. When I click the button it gives me an unhandled exception error. Here is my code:
Public Class Form1
Sub outputFile()
Dim oWrite As System.IO.StreamWriter
oWrite = System.IO.File.CreateText("C:\sample.txt")
oWrite.WriteLine(fullNameBox.Text)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
outputFile()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class

Have you tried stepping through your application to see where the error is? With a quick glance, it looks like you might need to use System.IO.File on the fourth line (oWrite = IO.File...) instead of just IO, but I haven't tried to run it.

Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.FileName = ""
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(SaveFileDialog1.FileName.Trim, FileMode.Create)
Dim sr As New StreamWriter(fs)
sr.Write(TextBox1.Text)
fs.Flush()
sr.Close()
fs.Close()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(OpenFileDialog1.FileName.Trim, FileMode.Open)
Dim sw As New StreamReader(fs)
TextBox1.Text = sw.ReadToEnd
fs.Flush()
sw.Close()
fs.Close()
End If
End Sub
End Class
this is a complete functional program if you want, you just need to drag drop a textbox, openfiledialog, and a savefiledialog.
feel free to play around with the code.
enjoy
by the way, the problem in your code is that you "must" close filestream when your done using it, doing so will release any resource such as sockets and file handles.

The .net framework is a very powerful framework. In the same way (however) it has easy and convenient methods for simple tasks. Most individuals tend to complicate things in order to display knowledge. But less code = less processing = faster and more efficient application (sometimes) so the large above method may not be suitable. Along with that, the above mentioned method would be better off written as a sub or if returning something then a function.
My.Computer.FileSystem.WriteAllText("File As String", "TextAsString", Append as Boolean)
A general Example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", "this is what I would like to add", False)
this is what I would like to add
can be changed to the current text of a field as well.
so a more specific example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", fullNameBox.text, True)
If you would like to understand the append part of the code
By setting append = true you are allowing your application to write the text at the end of file, leaving the rest of the text already in the file intact.
By setting append = false you will be removing and replacing all the text in the existing file with the new text
If you don't feel like writing that part of the code (though it is small) you could create a sub to handle it, however that method would be slightly different, just for etiquette. functionality would remain similar. (Using StreamWriter)
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", append as boolean)
objWriter.WriteLine(textboxname.Text)
objWriter.Close()
End Sub
The Specific Example would be
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", False)
objWriter.WriteLine(fullnamebox.Text)
objWriter.Close()
End Sub
then under the button_click event call:
writetext()
You can take this a step further as well. If you would like to create a more advabced Sub to handle any textbox and file.
Lets say you plan on having multiple separate files and multiple fields for each file (though there is a MUCH cleaner more elegant method) you could create a function. {i'll explain the concept behind the function as thoroughly as possible for this example}
below is a more advanced sub demonstration for your above request
Private Sub WriteText(Filename As String, app As Boolean, text As String)
Dim objWriter As New System.IO.StreamWriter(Filename, app)
objWriter.WriteLine(text)
objWriter.Close()
End Sub
What this does is allows us to (on the same form - if you need it global we can discuss that another time, it's not much more complex at all) call the function and input the information as needed.
Sub Use -> General Sample
WriteText(Filename As String, app As Boolean)
Sub Use -> Specific Sample
WriteText("C:\text.txt, False, fullnamebox.text)
But the best part about this method is you can change that to be anything as you need it.
Let's say you have Two Buttons* and **Two Boxes you can have the button_event for the first button trigger the above code and the second button trigger a different code.
Example
WriteText("C:\text2.txt, False, halfnamebox.text)
The best part about creating your own functions and subs are Control I won't get into it, because it will be off topic, but you could check to be sure the textbox has text first before writing the file. This will protect the files integrity.
Hope this helps!
Richard Sites.

Related

Could someone explain where are the errors in this code in vb.net

I'm new to this site and also a newbee in vb.net, I created a simple form in vb.net, a form with 3 buttons, by clicking Button1 Species1.txt is created, and by clicking Button2 the lines in Species1.txt are copied in a String Array called astSpecies(), and by Button3 the String Array is copied in a new file, named Species2.txt, below is the code.
Public Class Form4
Dim astSpecies() As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myStreamWriter = New StreamWriter("C:\Users\Administrator\Documents\species1.txt", True)
myStreamWriter.WriteLine("Pagasius pangasius")
myStreamWriter.WriteLine("Meretrix lyrata")
myStreamWriter.WriteLine("Psetta maxima")
myStreamWriter.WriteLine("Nephrops norvegicus")
myStreamWriter.WriteLine("Homarus americanus")
myStreamWriter.WriteLine("Procambarus clarkii")
myStreamWriter.Close()
MsgBox("list complete")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myStreamReader = New StreamReader("C:\Users\Administrator\Documents\species1.txt")
Dim i As Integer
Dim stOutput As String
stOutput = ""
Do While Not myStreamReader.EndOfStream
astSpecies(i) = myStreamReader.ReadLine
stOutput = stOutput & astSpecies(i) & vbNewLine
i = i + 1
Loop
myStreamReader.Close()
MsgBox(stOutput)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim myStreamWriter = New StreamWriter("C:\Users\Administrator\Documents\species2.txt", True)
Dim o As Integer
Do While o <= astSpecies.Length
myStreamWriter.WriteLine(astSpecies(o))
o = o + 1
Loop
myStreamWriter.Close()
End Sub
End Class
First of all, you should make a few settings when it comes to VB.Net. 1.) set Option Strict to On 2.) remove the VB6 namespace. VB6 is the old Visual Basic. There are many functions in this that are inefficient from today's perspective. So please do not write MsgBox() but MessageBox.Show("").
(If you still need control characters such as NewLine or Tab, you can set a selective reference with Imports Microsoft.VisualBasic.ControlChars. Sounds contradictory, but it is useful, because why should you also write ChrW(9), it is not legible.)
I quickly started a project myself and wrote whatever you wanted.
I still don't quite understand why you first write things into a text file, then read them out, and then write that into a second text file – I want to say: where do the strings originally come from? The strings must have been there already? Anyway, I filled a List(of String) in the Button2_Click procedure. This has the advantage that you don't have to know in advance how many strings are coming, and you can sort them later and so on ...
You should also discard all Writers when you no longer need them. So use Using. Otherwise it can happen that the written files are not discarded and you can no longer edit the file.
Imports Microsoft.VisualBasic.ControlChars
Imports Microsoft.WindowsAPICodePack.Dialogs
Public NotInheritable Class FormMain
Private Path As String = ""
Private allLines As New List(Of String)
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BackColor = Color.FromArgb(161, 181, 165)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using OFolderD As New CommonOpenFileDialog
OFolderD.Title = "Ordner auswählen"
OFolderD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
OFolderD.IsFolderPicker = True
If OFolderD.ShowDialog() = CommonFileDialogResult.Ok Then
Path = OFolderD.FileName
Else
Return
End If
End Using
Path &= "\Data.txt"
Using txtfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True)
txtfile.WriteLine("Pagasius pangasius")
txtfile.WriteLine("Meretrix lyrata")
txtfile.WriteLine("Psetta maxima")
txtfile.WriteLine("Nephrops norvegicus")
txtfile.WriteLine("Homarus americanus")
txtfile.WriteLine("Procambarus clarkii")
txtfile.Close()
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Path, System.Text.Encoding.UTF8)
If RAT.Length = 0 OrElse RAT.Length = 1 Then
MessageBox.Show("The File only contains 0 or 1 characters.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand)
Return
End If
allLines.AddRange(RAT)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Pfad_txt As String = Path.Substring(0, Path.LastIndexOf("\"c)) & "\Data2.txt"
Using txtfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Pfad_txt, True)
For Each Line As String In allLines
txtfile.WriteLine(Line)
Next
txtfile.Close()
End Using
End Sub
End Class
By the way: I use a FolderBrowserDialog in the Button1_Click procedure. This should be done so that the program also runs properly on other PCs. In order to be able to use the FBD, you have to download Microsoft.WindowsAPICodePack.Dialogs in Visual Studio's own Nuget package manager.
how to set Option Strict to On
How to uncheck VB6.
how to install FolderBrowserDialog in Visual Studio
Button1
If you want to use a StreamWriter it should be disposed. Classes in the .net Framework that have a Dispose method may use resources outside of the framework which need to be cleaned up. The classes shield you from these details by provided a Dispose method which must be called to properly do the clean up. Normally this is done with Using blocks.
I used a string builder which saves creating and throwing away a string each time you change the string. You may have heard that strings are immutable (cannot be changed). The StringBuilder class gets around this limitation. It is worth using if you have many changes to your string.
The File class is a .net class that you can use to read or write files. It is not as flexible as the stream classes but it is very easy to use.
Button 2
When you declared your Array, you declared an array with no elements. You cannot add elements to an array with no space for them. As Daniel pointed out, you can use the .net class List(Of T) The T stands for Type. This is very good suggestion when you don't know the number of elements in advance. I stuck with the array idea by assigning the array returned by File.ReadAllLines to the lines variable.
You get the same result by simply reading all the text and displaying it.
Button 3
Again I used the File class here which allows you to complete your task in a single line of code. Using 2 parameters for the String.Join method, the separator string and the array to join, we reproduce the original file.
Private SpeciesPath As String = "C:\Users\maryo\Documents\species1.txt"
Private lines As String()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New StringBuilder
sb.AppendLine("Pagasius pangasius")
sb.AppendLine("Meretrix lyrata")
sb.AppendLine("Psetta maxima")
sb.AppendLine("Nephrops norvegicus")
sb.AppendLine("Homarus americanus")
sb.AppendLine("Procambarus clarkii")
File.WriteAllText(SpeciesPath, sb.ToString)
MsgBox("list complete")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
lines = File.ReadAllLines(SpeciesPath)
MessageBox.Show(String.Join(Environment.NewLine, lines))
'OR
MessageBox.Show(File.ReadAllText(SpeciesPath))
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
File.WriteAllLines("C:\Users\maryo\Documents\species2.txt", lines))
End Sub

Download, get the filename and execute the file

I am posting here to ask you for help, thank you first of all for reading my message and being able to help me. :)
So here's the problem, I have a little program that I'm creating, in this one, I integrated a button that normally allows to download a tool to run it.
However the link of the file does not point directly in .exe it is a link like this one :
mydomain.com/file/file48.php
The problem is that I manage to get the file, but this one is named file48.php and gets the extension of a php file, what I would like is to get the original name of the downloaded .exe file in order to be able to execute it within my application.
Here is the current code I'm using :
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim client As New WebClient
AddHandler client.DownloadFileCompleted, AddressOf client_DownloadFileCompleted
client.DownloadFileAsync(New Uri("https ://mydomain.com/files/index.php"), fileName, filename)
End Sub
Private Sub client_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
Dim client = DirectCast(sender, WebClient)
client.Dispose()
Dim filename As String = CType(e.UserState, String)
End Sub
Thanks a lot for your help, I've been searching for hours without much success...

How to save a txt file to a predetermined location in vb 2010?

Hi i have a textbox which displays a bunch of names on it. The names are within a string called "strNames". I'm trying to have a save button which saves the names as a txt file in a predetermined location. Here is the code for the save button. It creates the file but without the list of names. please help!
Given the fact that your strNames is an array of strings then you could use File.WriteAllLines, no need to use a StreamWriter here
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
File.WriteAllLines("C:\Test.txt", strNames)
End Sub
This has an advantage against the StreamWriter approach if you don't need particular processing to your input array before writing it to file, no foreach around the array strings and also you don't need to encapsulate the StreamWriter in a Using statement to ensure a proper release of the system resources
You need to write to the file and then call Close() on the StreamWriter
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim w As IO.StreamWriter
w = New IO.StreamWriter("C:\Test.txt")
' strNames is an array so you have to iterate through the array and write each element
For Each item As String In strNames
w.WriteLine(item)
Next
w.Close()
End Sub
Make sure to use Try/Catch blocks in case any exception occurs during accessing and writing to the file.
Also, when you use resources such as Files, make sure to properly dispose of the object that's connected to the resource. Using the 'Using' statement is a great and safe way to do that. Here's an example of both in action.
Sub WriteToFile()
Dim strNames As String() = {"John", "Jimmy", "Joe"}
Try
Using oWriter As New IO.StreamWriter("C:\testFile.txt")
For Each strName As String In strNames
oWriter.WriteLine(strName)
Next
End Using
Catch ex As Exception
HandleException(ex)
End Try
End Sub

Visual Basic Form. How to let users save text file where they want

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
Dim CurrentDir As String = Environment.CurrentDirectory
Dim OutputFile2 As String = IO.Path.Combine(CurrentDir, "input.txt")
IO.File.WriteAllLines(OutputFile2, Result1.Lines)
End Sub
Right now, I have coding that saves a text file in the current directory. However, I want to have a browse button for users so that they can pick where this text file is saved. How do I proceed this?
I was trying it by my self and I'm having a trouble with using save file dialog. If you can teach me how to use a save file dialog or anyway to write save browse button, I would very appreciate it!
The documentation for the SaveFileDialog object contains an example.
Here is a tutorial on how to implement SaveFileDialog using Toolbox in Visual Studio like you mentioned. The code sample is in C# but it can be easily converted to VB.
Link: www.dotnetperls.com/savefiledialog
Private Sub button1_Click(sender As Object, e As EventArgs)
' When user clicks button, show the dialog.
saveFileDialog1.ShowDialog()
End Sub
Private Sub saveFileDialog1_FileOk(sender As Object, e As CancelEventArgs)
' Get file name.
Dim name As String = saveFileDialog1.FileName
' Write to the file name selected.
' ... You can write the text from a TextBox instead of a string literal.
File.WriteAllText(name, "test")
End Sub

Error with code?

Hi can anyone tell me why the following dose not work:
(p.s I dont want the file to append upon clicking abutton just upon clicking the checkbox.
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
Dim FILE_NAME As String = "C:\RXF\log.txt"
'Adding items for AutoCAD 2006...
If CheckBox1.CheckState = CheckState.Checked Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine("module: 4FNV-67-5H")
objWriter.Close()
End If
End Sub
End Class
Not reproducible, even with your exact code as posted. This works perfectly fine for me, creating a text file in the specified location if one does not exist and appending the specified text to the end of the file.
The only thing I suggest is wrapping your StreamWriter object in a Using statement to ensure that its Dispose method always gets called, even if an exception is thrown (which is all the more likely when you're doing disk I/O). So, your existing code would simply change to:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
Dim FILE_NAME As String = "C:\RXF\log.txt"
''#Adding items for AutoCAD 2006...
If CheckBox1.CheckState = CheckState.Checked Then
Using objWriter as New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine("module: 4FNV-67-5H")
objWriter.Close()
End Using
End If
End Sub
Also, if you anticipate this method getting called a lot (i.e., the user clicking and unclicking and clicking the checkbox repeatedly), you might consider creating the StreamWriter object once and saving it as a private class-level variable, instead of creating and disposing of it each time the method is called. Then you just have to make sure that you dispose of it whenever your class (presumably the containing form) is disposed.