Visual Basic Form Coding (how to set a directory) - vb.net

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
Dim Newline As String
Newline = System.Environment.NewLine
System.IO.File.WriteAllLines("C:\Users\Sang\Desktop\filename.txt", Result1.Lines)
System.IO.File.AppendAllLines("C:\Users\Sang\Desktop\filename.txt", Result2.Lines)
System.IO.File.AppendAllLines("C:\Users\Sang\Desktop\filename.txt", values.Lines)
End Sub
This is my coding for making a text file on my desktop. However, my friend can not run this code because this code is only for myself as you can see above. I would like to use a folderbroswerdialog to generalize this coding for everyone. To be specific, if a user pressed this button on the form, folder browser should ask him where he wants to save this text file and text file should be saved in the directed folder or desktop. I tried to do it on my own by looking at many youtube videos and resources but I failed. How should I proceed this?

You can use the Environment.SpecialFolder Enumeration which contains the ubications of the system's directories that you can retrieve using Environment.GetFolderPath method :
Dim DesktopDir As String =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Then you can use the Path.Combine method to properlly combine a directory/file path:
Dim OutputFile As String =
IO.Path.Combine(DesktopDir, "filename.txt")
Then:
IO.File.WriteAllLines(OutputFile, "Text Here")

Take a look here for using the FolderBrowserDialog:
http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog(v=vs.110).aspx
PERFECTLY great examples there.

Related

How do I specify relative file path in VB.net

I have a Webbrowser control in a form which displays a pdf file. I have to specify the URL as the file location on my computer.
eg.
E:\Folder\Manual.pdf
Both the pdf file and the program are in the same folder.
How do I specify the URL so that when I move the folder onto another drive, it opens the same pdf file?
The location of your application is
Dim path as String = My.Application.Info.DirectoryPath
The you could use:
Dim pdffile as String = IO.Path.Combine(path, "pdffile.pdf")
WebBrowser1.Navigate(pdffile)
If I understand you correctly, then:
Dim myPdf As String =
IO.Path.Combine(IO.Directory.GetParent(Application.ExecutablePath).FullName, "myPdfFile.pdf")
Another way you could do it is by using something like the code below;
Private Sub FamilyLocateFile_Click(sender As Object, e As EventArgs) Handles FamilyLocateFile.Click
If LocateFamilyDialog.ShowDialog = DialogResult.OK Then
FamilyWMP.URL = LocateFamilyDialog.FileName
ElseIf LocateFamilyDialog.ShowDialog = DialogResult.Cancel Then
MsgBox(MsgBoxStyle.Critical, "Error!")
End If
End Sub
What this will do is play a file in a Windows Media Player ActiveX object. The file can be selected with an OpenFile Dialog, which in this case is called LocateFamilyDialog. You don't need the ElseIf part of the statement, but you will need to insert an open file dialog and a control that can display PDFs. I think it'll work with WebBrowsers, but I'm not sure.

How to make textfile to save in program directory in Visual Studio

As i have abandoned the array approach to the problem, i need to know how to make listbox to save in textfile always in program's directory so it can be used/accessed to populate a different listbox, any ideas? Below is my code.
SaveFileDialog1.Filter = "Text files (.txt)|.txt"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName <> "" Then
Using SW As New IO.StreamWriter(SaveFileDialog1.FileName, False)
For Each itm As String In Me.ListBox1.Items
SW.WriteLine(itm)
Next
End Using
End If
A little bit of research on your part would've helped you understand what you are trying to accomplish better.
How do I get Program Data directory? My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
How do I Write multiple lines to file? File.WriteAllLines()
How do I Read multiple lines from a file? File.ReadAllLines()
Once you understand the basics you can easily put them together
Create two List boxes, and one button on your WinForm:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.
'Get the Program Data Directory (This is hidden by default by the OS.)
Dim strPath As String = My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
Dim fileName As String = "myFile.txt"
Dim fullPath = Path.Combine(strPath, fileName)
Dim data As String() = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}
'Save the items to ListBox1 First
For Each item As String In data
ListBox1.Items.Add(item)
Next
'Now write the items to the textfile, line by line.
File.WriteAllLines(fullPath, data)
'Read all lines we just saved and load them onto an array of strings.
Dim tempAllLines() As String = File.ReadAllLines(fullPath)
'Display each on ListBox2 by iterating the array.
For Each line As String In tempAllLines
ListBox2.Items.Add(line)
Next
End Sub
Here, I created this form so you can get an idea of what i'm referring to.
You can get the path to the current executable's folder like this:
folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
However, that will only work if the executable is a .NET assembly. Otherwise, you could use the first argument in the command line (which is the full executable file path), like this:
folderPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()(0))
If, on the other hand, you want to get the path of the current assembly (which may be different than the executable that loaded it) you could do this:
folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Or, if you want to just get the current directory, you could use this:
folderPath = Directory.GetCurrentDirectory()
Once you have the folder path, you can add the file name to it with Path.Combine, like this:
filePath = Path.Combine(folderPath, fileName)
However, it's not recommended that you write data directly to the program's running path, since the user may not have permission to write to that folder. Using the program data folder would certainly be better, but even that can be risky:
folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyAppName")
The recommended place to store data from .NET apps is Isolated Storage.

How to save a content of a specific textbox to file using VB.net

Good morning everyone,
I'm working on my finals project in visual basic and i want to implement a save file option.
Right now the application has 2 textboxes (not richtextbox) which are the input and output of information.
What i want to do is save only the content of the output textbox. I managed to get it to save something to file but when its opened it always turns out to be empty.
the code example of the save file button is below, i have a feeling its not saving the content because it is not specified, yet i have no idea how to specify to only save the content of the one textbox even with the many hours of forum / google searching ive done to try and figure out on my own.
Dim myStream As Stream
Dim nsavetxtoutput As New SaveFileDialog()
'|All files (*.*)|*.*
nsavetxtoutput.Filter = "txt files (*.txt)|*.text"
nsavetxtoutput.FilterIndex = 2
nsavetxtoutput.RestoreDirectory = True
If nsavetxtoutput.ShowDialog() = DialogResult.OK Then
myStream = nsavetxtoutput.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
Any and all insight would be much appreciated!
Thank you guys!
The Program allowed to save only the contents of the textbox with this function - Thanks very much everyone who replied. it helped out allot!
Private Sub NOTEPAD_BUTTON(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTSave2Notepad.Click
Dim nsavetxtoutput As New SaveFileDialog()
nsavetxtoutput.Filter = "txt files (*.txt)|*.text"
nsavetxtoutput.FilterIndex = 2
nsavetxtoutput.RestoreDirectory = True
If nsavetxtoutput.ShowDialog() = DialogResult.OK Then
IO.File.WriteAllText(nsavetxtoutput.FileName, txtoutput.Text)
End If
End Sub
Try this:
If nsavetxtoutput.ShowDialog() = DialogResult.OK Then
IO.File.WriteAllText(nsavetxtoutput.FileName, TextBox2.Text)
End If
Where TextBox2 is your output TextBox.
More information at MSDN Documentation.
You can write to a file using File.WriteAllText method. It takes two parameters. The first is the path to the file, which you get from the SaveFileDialog. The second is the value you want to write to the file.
See the article on MSDN

Populate Listbox with directory contents but only accept certain extensions

So, basically I drag in a folder onto the form, and a Listbox populates with the paths of the files inside. I've managed to make the Listbox accept only .MP3 paths, but how can I add more accepted extensions?
Private Sub Form1_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
If Directory.Exists(path) Then
'Add the contents of the folder to Listbox1
ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*"))
As you can see in the last line above, paths in the folder having .mp3 extension are accepted. How do I add more accepted extensions, like .avi, .mp4 etc?
I've tried ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*" + "*.mp4*"))
I've also tried ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*" , "*.mp4*"))
No luck !
You should create a for loop, test your extension, and then add it or not...
Something like;
Dim AllowedExtension As String = "mp3 mp4"
For Each file As String In IO.Directory.GetFiles("c:\", "*.*")
If AllowedExtension.Contains(IO.Path.GetExtension(file).ToLower) Then
listbox1.items.add(file)
End If
Next
Or even more dirty;
IO.Directory.GetFiles(path, "*.mp*")
Or do it twice;
add
ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*"))
and
ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp4*"))

how do I put contents of C: into an array?

Am learning arrays at the moment and I have the below piece of code that goes through drive C: and displays the files in in a list box.
I want to try and expand it to use array.sort so that it gets the files, puts them into an array, and then I can sort by filename or file size. I have been rattling my brain over this - as to how do I put the files into an array.
Would like an explanation if possible as more interested in learning it rather than the answer.
Thanks!
Private Sub btnclick_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclick.Click
Call Clearlist()
Dim strFilesinfo As System.IO.FileInfo
Dim strlength As Double = 0
Dim strname As String = ""
For Each strFiles As String In My.Computer.FileSystem.GetFiles("c:\")
strFilesinfo = My.Computer.FileSystem.GetFileInfo(strFiles)
strlength = strFilesinfo.Length
strname = strFilesinfo.Name
lstData.Items.Add(strname & " " & strlength.ToString("N0"))
Next
End Sub
End Class
To allow the data to be sortable, you'd need to be displaying something that could treat that information separately (i.e. a class or structure). You might also find that a different type of control, such as a DataGridView might be easier to get to grips with.
The .Net framework does define an interface, IBindingList which collections can implement to show that they report, amongst other things, sorting.
I'm providing this as a sample for learning purposes but it should not be used as-is. Getting every file from the entire C:\ should not be done like this. Aside from the performance issues there are windows security limitations that won't actually let you do this.
The FileList being populated here is getting just the TopDirectoryOnly. If you change that input to "AllDirectories" it will get all the subdirectories but it will fail as I stated before.
Dim path As String = "C:\"
Dim dir As New System.IO.DirectoryInfo(path)
Dim fileList = dir.GetFiles("*.*", IO.SearchOption.TopDirectoryOnly)
Dim fileSort = (From file In fileList _
Order By file.Name _
Select file.Name, file.Length).ToList
For Each file In fileSort
With file
lstData.Items.Add(String.Format("{0} {1}", .Name, .Length.ToString("N0")))
End With
Next file
Just change the Order By in the LINQ query to change how the sorting is done. There are many other ways to do the sorting but LINQ will handle it for you with very little code.