Error with code? - vb.net

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.

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

How to pass ListBox selected item into file?

What I have:
Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged
Dim curItem As String = ChooseProgram.SelectedItem.ToString()
End Sub
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curitem.string")
jhin.Close()
End Sub
I just want to write the string into the file.
How is that possible?
Thx for ur help!
Hannir
UPDATE:
' Ensure an item is selected
If ChooseProgram.SelectedItem Is Not Nothing Then
curItem = ChooseProgram.SelectedItem.ToString()
End If
I get an error here.
"The Is operator does not accept operands of type " integer " . The operands must be reference types, or permit types , NULL values ​​."
Really thx for ur quick help! #Pro Grammer
If you just click Install, and nothing is selected, it ends in an error. So is it possible to say "You need to select an item before" or the Install button is just clickable when selected an item?
For starters you have to move the declaration of the curItem variable out of the SelectedIndexChanged method, to what's called Class level.
As it stands your variable is accessible within your SelectedIndexChanged method only, whereas if you move it to class level it will be accessible by everything within that class (the class in this case is your Form). You then just modify the variable from your SelectedIndexChanged method.
Dim curItem As String = "" 'We'll start with an empty string.
Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged
curItem = ChooseProgram.SelectedItem.ToString()
End Sub
Now you will be able to access the variable from your button and write it to a file.
The last thing you have to do is to close the StreamWriter that you create so that it will release the lock on the file. The easiest and best way to do so is wrapping it in an Using/End Using block.
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Using jhin As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curItem)
End Using
End Sub
EDIT:
To make your button clickable only when an item is selected, first set the button's Enabled property to False via the Property Window in the designer, then use this code in the SelectedIndexChanged event:
Install.Enabled = ChooseProgram.SelectedIndex >= 0
If ChooseProgram.SelectedIndex < 0 Then Return
curItem = ChooseProgram.SelectedItem.ToString()
This is one option:
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Dim curItem as String = ""
' Ensure an item is selected
If ChooseProgram.SelectedItem IsNot Nothing
curItem = ChooseProgram.SelectedItem.ToString()
End If
' Double checking valid input
If String.IsNullOrWhiteSpace(curItem) Then
' Handle empty input - Display message, etc
' Exit Sub (unless bat handles empty)
End If
Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curItem)
jhin.Close()
End Sub
Instead of using the ChooseProgram_SelectedIndexChanged event, you can deal with it from here, since you aren't performing any other actions in that method. If you wanted to still use that event, you would assign the string value into a field which could be accessed across the class. Check out Visual Vincent's answer for this example, and also of a Using block, which removes the need to call jhin.Close() manually and also provides a much clearer format

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

Streamwriter will not save to FileName entered by User with Default var.FileName initiated - VB.NET

I am new here, and relatively new to VB.NET. I have a specific problem with getting my StreamWriter to work properly. One of the requirements of my project is to give the file a default name when the user clicks the Save button, which I have done by setting mysave.Filename = "MyLog.log". I call a new instance of my streamwriter trying to save to the filename specified by the user (mySave.Filename again), but every time, it saves to the default MyLog.log file. I have pasted my code below.
If someone could tell me how I can make sure the data is being saved to the value entered by the user for File name, that would be greatly beneficial. Also, I apologize for the code format, its not perfectly readable, but I'm trying to learn how to use the 4 space indents to my advantage!!
Thanks!
Imports System.IO
Public Class Form1
Dim Initial As String = "C:\Users\Brian Frick\Documents\Visual Studio 2010\Projects\HW5_Frick_Creator\HW5_Frick_Creator\bin\Debug" 'give variable for full path without log file
Dim Fullpath As String = "C:\Users\Brian Frick\Documents\Visual Studio 2010\Projects\HW5_Frick_Creator\HW5_Frick_Creator\bin\Debug\MyLog.log" 'give one path for full path
Dim filewriter As New StreamWriter(Fullpath, True)
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit() ' quit application
filewriter.Close()
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
Dim mySave As New SaveFileDialog
mySave.Filter = "LOG File (*.log)|*.log" 'set filter to .log
mySave.DefaultExt = "log" 'set default extension
mySave.InitialDirectory = Initial 'set default directory
mySave.FileName = "MyLog.log"
mySave.OverwritePrompt = True ' make sure to ask user if they want to over write
If mySave.ShowDialog() = DialogResult.OK Then
Dim filewriter As New StreamWriter(mySave.FileName, True)
filewriter.Close()
'filewriter = New StreamWriter(mySave.FileName, True)
'filewriter.Close() 'close filewriter to allow access to write directory
'Dim Stream As New StreamWriter(mySave.FileName, True) 'save file to path chosen by user in SaveDialog
'Stream.Close() ' Close stream to allow access to directory
' filewriter.Close()
Else
'dialog cancelled - no action
End If
filewriter.Close()
filewriter = New StreamWriter(Fullpath, True) 're initiate filewriter to be used in successive iterations through the program without error
End Sub
Private Sub SavingsDepositBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SavingsDepositBtn.Click
'write to file for SavDep
filewriter.WriteLine("SavDep")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub SavingsWithdrawBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SavingsWithdrawBtn.Click
'write to file for SavWith
filewriter.WriteLine("SavWith")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub CheckDepsotBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckDepsotBtn.Click
'write to file for CheckDep
filewriter.WriteLine("CheckDep")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub CheckWithdrawBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckWithdrawBtn.Click
'write to file for CheckWith
filewriter.WriteLine("CheckWith")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
End Class
the general way you are using the filewriter won't work, and there are some other serious issues like that there are two 'FileWriter' variables with overlapping scope.
for your save routine, you can't just re-instantiate your filewriter to point it to a different path. that will destroy all the data that had been in the underlying stream, so you are just saving nothing.
try caching the data in memory while the program is running, and don't create the stream until you are ready to write all the data to it, and it to a file, all in one go. your current approach makes it very hard to prevent leaking handles to the log files, so if the app crashes the user will have to reboot to release the write lock before they can run it again. look into the 'using' construct and 'Try... Finally'

Pressing a button in visual basic

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.