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

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

Related

how to export listbox to notepad in vb?

i have contains listbox. how to export listbox to notepad in vb? Please advise me
Notepad typically reads and writes plain old .txt files. These can be written with a standard StreamWriter. Just iterate over your ListBox and write each item to your file:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim txtFile As String = "C:\Users\mikes\Documents\Test.txt"
Using sw As New IO.StreamWriter(txtFile, False)
For Each item As String In ListBox1.Items
sw.WriteLine(item)
Next
End Using
End Sub
If you don't want to hard-code a filename, then use a SaveFileDialog to get a filename from the user.

Why Is A FilePath Item With ~$ Added To ListBox

I am adding file paths from a folder to a List Box which are then opened as text in a Rich Text Box. I have used the same syntax as the code below for achieving the same purpose in another List Box and it works just fine. But, in the current example, I have two files in the default MyProjects folder (i.e. default folder is created by my app), but when I add the file paths from the folder as items to the List Box, I get a third item with ~$ in the file path? This item is obviously some kind of repetition of the first file path in the list? The two files in the default folder are also created by my app so, if this is a file access issue, I don't understand why I wouldn't have access to a file created by my app? Can anyone give me a clue what's happening here?
What I have Tried:
I have tried debugging to check where the extra file path is coming from. As far as I can tell, it is being created when I add the file paths to the List Box? i.e. commenting out the code for adding the items to the List Box stops all items being added, but doesn't tell me where this extra item is coming from?
The "Extra Item" Issue:
System.Windows.Forms.ListBox+ObjectCollectionC:\Users\username\Documents\MySolution\MyProjects\RTFdoc.rtf
C:\Users\username\Documents\MySolution\MyProjects\Testdoc.rtf
C:\Users\username\Documents\MySolution\MyProjects~$Fdoc.rtf
The Code:
lbxName.Items.AddRange(Directory.GetFiles("C:\Users\" + username + "\Documents\MySolution\MyProjects"))
lbxName.SelectedIndex = 0
Code For Loading:
For Each item In lbxName.SelectedItems
RTB.LoadFile(lbxName.SelectedItem, RichTextBoxStreamType.RichText)
Next
I cannot reproduce the error in the following code.
Private Sub FillListBox()
ListBox1.Items.AddRange(Directory.GetFiles("C:\Users\" & username & "\Documents\MySolution\MyProjects"))
ListBox1.SelectedIndex = 0
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FillListBox()
End Sub
Please read the comments in the following code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each item In ListBox1.SelectedItems
'The following will overwrite the contents of the RichTextBox on each iteration
'This overload of LoadFile will only handle .rtf files
RichTextBox1.LoadFile(item.ToString)
Next
End Sub
I suggest you set the SelectionMode property to One in the designer and do the following.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
RichTextBox1.LoadFile(ListBox1.SelectedItem.ToString)
End Sub
Try to use as follows:
Directory.GetFiles("C:\Users\" & username & "\Documents\MySolution\MyProjects").Where(Function(f)
Return New IO.FileInfo(f).Attributes & IO.FileAttributes.Hidden & IO.FileAttributes.System = 0

opening a file from a path written in a text file?

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim objectreader As New System.IO.StreamReader(TextBox1.Text)
System.Diagnostics.Process.Start("TextBox2.Text = objectreader.ReadToEnd()")
objectreader.Close()
End Sub
End Class
I am trying to read from a text file where i have written a path to a file. I have been able to open a file using System.Diagnostics.Process.Start() and I have been able to read from a text file using StreamReader but I could not relate to it. How do I take the text from the text file and put it in the System.Diagnostics.Process.Start("here") to open the file. I am using vb.net visual studio 2013.
Remove the quotes. You aren't providing a string literal, you're providing the result of a method call:
TextBox2.Text = objectreader.ReadToEnd()
System.Diagnostics.Process.Start(TextBox2.Text)

Trouble saving ALL listbox data

Ok, so i'm trying to make an Injector. To load the DLLs, I used a File Dialog to select the DLL then write the info to a List Box. Now I want to save the data in the list box and reload the past data on the Form Load, but every method I have tried only saves the name of the DLL not the other info such as Location.
I would like to have no external files IF possible. Any solutions?
Cheers.
Edit: Source code for Open File Dialog
Private Sub OpenFileDialog1_FileOk(sender As Object, e As
System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim FileName As String = OpenFileDialog1.FileName.Substring(OpenFileDialog1.FileName.LastIndexOf("\"))
Dim DLLfileName As String = FileName.Replace("\", "")
ListBox1.Items.Add(DLLfileName)
dlls.Add(DLLfileName, OpenFileDialog1.FileName)
End Sub

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.