Creating folders using vb.net - vb.net

I'm starting on a program that creates a folder
this is what i currently have, now what i want to do is to have two textboxes, one textbox is for the directory and the other is for the folder name, how can i implement that here?
Private Sub CreateBTN_Click(sender As Object, e As EventArgs) Handles CreateBTN.Click
Dim Path As String = txttargerdirectory.Text
If Not Directory.Exists(Path) Then
Directory.CreateDirectory(Path)
MsgBox("folder created")
Else
MsgBox("Folder already exist")
End If
End Sub

Are you looking for something like this?
Private Sub CreateBTN_Click(sender As Object,
e As EventArgs) Handles CreateBTN.Click
Dim sPath As String = IO.Path.Combine(txtPath.Text, txtFolderName.Text)
If Not IO.Directory.Exists(sPath) Then
IO.Directory.CreateDirectory(sPath)
MsgBox("folder created")
Else
MsgBox("Folder already exist")
End If
End Sub

Related

Saving and reading files on Visual basic

Hi I'm creating a "Toilet paper tracker" on visual basic and I'm struggling with saving and reading files, I know I am missing stuff. The user should be able to login and input a threshold and when reached a warning will pop up saying "buy more toilet paper" (i haven't coded this yet) and the user can add to create a total and subtract from it too. The user should also be able to save the total to a file and I want the program to be able to read the file and change the total if the user wants to add or subtract again. It would be greatly appreciated if you pointed me in the right direction, I'm only young so it's relatively simple. Here is my program :)
Imports System.IO
Public Class frmTPT
Private Sub TPT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call loadchangetotal()
End Sub
Sub loadchangetotal()
cboChange.Items.Add("Add to Total")
cboChange.Items.Add("Subtract from Total")
End Sub
Private Sub cboVenue_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChange.SelectedIndexChanged
If cboChange.Text = "Add to Total" Then
Dim frmChangeACopy As New frmChangeA
frmChangeACopy.Show()
Me.Hide()
ElseIf cboChange.Text = "Subtract from Total" Then
Dim frmChangeSCopy As New frmChangeS
frmChangeSCopy.Show()
Me.Hide()
End If
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtThreshold.Text = ""
cboChange.Text = ""
txtTotal.Text = ""
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnReadTotal_Click(sender As Object, e As EventArgs) Handles btnReadTotal.Click
Dim FileReader As StreamReader
Dim result As DialogResult
result = OpenFileDialog1.ShowDialog
If result = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.Filename)
txtFileContent.Text = FileReader.ReadToEnd() 'i want to be able to read a
'previously saved total so that
FileReader.Close() 'it can be used to find the new total
'after it has been added to
End If 'or subtratced
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Call SaveFile()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim A, S, NewTotal As Integer
A = Val(frmChangeA.txtAdd.Text)
S = Val(frmChangeS.txtSubtract.Text)
NewTotal = A - S 'I want to be able to load a previously saved total if one exists and add and
'subtract from it
End Sub
End Class
Sub SaveFile()
Dim FileWriter As StreamWriter
Dim results As DialogResult
results = SaveFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
FileWriter.Write(txtFileContent.Text) ' is txtFileContent supposed to be
' the name of my textbox?
FileWriter.Close()
End If
End Sub
Design
You didn't mention if you were using .Net Core or 4.x. If the later, you can sometimes use the Insert Snippet functionality to learn how to do common tasks. For example in this case you could right click in the code editor and select Insert Snippet then Fundamentals then File System and finally Write text to a file. This will result in the following VB code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Unfortunately, this option doesn't work with .Net core since the My namespace wasn't ported to core.
The key point of this problem lies in reading and writing data from text. It is a clear idea to write two methods to achieve read and write.
You can refer to the following code. The two methods in the following example are WriteTotal(), ReadTotal().
Design:
Public Class Form1
Dim Oldtotal As Integer
Dim Newtotal As Integer
Private Sub btnLoadTotal_Click(sender As Object, e As EventArgs) Handles btnLoadTotal.Click
WriteTotal()
ReadTotal()
End Sub
Private Sub btnUpdateTotal_Click(sender As Object, e As EventArgs) Handles btnUpdateTotal.Click
cboChange.Text = Nothing
WriteTotal()
ReadTotal()
MsgBox("Inventory updated")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboChange.SelectedIndex = 0
ReadTotal()
End Sub
Sub WriteTotal()
Using swriter As IO.StreamWriter = New IO.StreamWriter("D:/paperstore.txt", False, System.Text.Encoding.UTF8)
If cboChange.Text = "Add to Total" Then
Newtotal = Oldtotal + CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
ElseIf cboChange.Text = "Subtract from Total" Then
If CType(txtThreshold.Text, Integer) > Oldtotal Then
swriter.WriteLine(Oldtotal)
MsgBox("buy more toilet paper")
Else
Newtotal = Oldtotal - CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
End If
Else
swriter.WriteLine(txtTotal.Text)
End If
End Using
End Sub
Sub ReadTotal()
Using sreader As IO.StreamReader = New IO.StreamReader("D:/paperstore.txt", System.Text.Encoding.UTF8)
Try
Oldtotal = sreader.ReadLine()
txtTotal.Text = Oldtotal
Catch ex As Exception
MsgBox(ex.Message)
End
End Try
End Using
End Sub
End Class

Directory.GetFiles Method Not Working In VB

I have created software with Visual Builder that cleans up your desktop. I have used the Directory.GetFiles method to move file types into certain directories. When I first coded it worked fine although I then got an error saying System.IO.IOException: 'Cannot create a file when that file already exists. Which I am not sure how to fix as I create the directory for the files with separate buttons as seen in the code.
I am also having issues with the other buttons which may be a result of the other error. When I go to clean the shortcuts which I programmed to move .lnk files into a Shortcuts folder none of them move into that folder unless they have previously been in that folder.
Full Code
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs)
MessageBox.Show("Desktop Cleaned")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim filePaths = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.png")
For Each filePath In filePaths
Dim filename = IO.Path.GetFileName(filePath)
Dim newPath = IO.Path.Combine("C:\Users\bj\Desktop\Pictures", filename)
IO.File.Move(filePath, newPath)
Next filePath
Dim filePaths2 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.jpg")
For Each filePath2 In filePaths2
Dim filename2 = IO.Path.GetFileName(filePath2)
Dim newPath2 = IO.Path.Combine("C:\Users\bj\Desktop\Pictures", filename2)
IO.File.Move(filePath2, newPath2)
Next filePath2
MessageBox.Show("Pictures Compiled And Cleaned")
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePaths3 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.lnk")
For Each filePath3 In filePaths3
Dim filename3 = IO.Path.GetFileName(filePath3)
Dim newPath3 = IO.Path.Combine("C:\Users\bj\Desktop\Shortcuts", filename3)
IO.File.Move(filePath3, newPath3)
Next filePath3
Dim filePaths6 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.url")
For Each filePath6 In filePaths6
Dim filename6 = IO.Path.GetFileName(filePath6)
Dim newPath6 = IO.Path.Combine("C:\Users\bj\Desktop\Shortcuts", filename6)
IO.File.Move(filePath6, newPath6)
Next filePath6
MessageBox.Show("Shortcuts Compiled And Cleaned")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim filePaths4 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.mp4")
For Each filePath4 In filePaths4
Dim filename4 = IO.Path.GetFileName(filePath4)
Dim newPath4 = IO.Path.Combine("C:\Users\bj\Desktop\Videos", filename4)
IO.File.Move(filePath4, newPath4)
Next filePath4
Dim filePaths5 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.avi")
For Each filePath5 In filePaths5
Dim filename5 = IO.Path.GetFileName(filePath5)
Dim newPath5 = IO.Path.Combine("C:\Users\bj\Desktop\Videos", filename5)
IO.File.Move(filePath5, newPath5)
Next filePath5
MessageBox.Show("Videos Compiled And Cleaned")
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Shortcuts")
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Videos")
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Pictures")
End Sub
End Class
Error Code
IO.File.Move(filePath, newPath) Returns The Error,
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim filePaths = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.png")
For Each filePath In filePaths
Dim filename = IO.Path.GetFileName(filePath)
Dim newPath = IO.Path.Combine("C:\Users\bj\Desktop\Pictures", filename)
IO.File.Move(filePath, newPath)
Next filePath
Error Message : System.IO.IOException: 'Cannot create a file when that file already exists.
Take a look at the documentation for File.Move - the example code checks if the file exists first and deletes it
Wa can extend this logic to maybe make for a nicer experience.
If IO.File.Exists(newPath) Then
Dim dr = MessageBox.Show($"File {newPath} exists, do you want to keep both files? The recently moved file will have a number added to its name", "", MessageBoxButtons.YesNoCancel)
Select dr
Case DialogResult.Cancel
Continue 'go to next loop iteration
Case DialogResult.No
IO.File.Delete(newPath)
Case DialogResult.Yes 'keep both
'Make the path eg kitten.1.jpg, kitten.2.jpg until we find a free name
Dim x = 0
Do
x += 1
newPath = IO.Path.ChangeExtension(newPath, i & IO.Path.GetExtension(newPath))
While IO.File.Exists(newPath)
End Select
End If

How to set download location with FolderBrowserDialog

I am trying to use FolderBrowserDialog to select the location where a file will be downloaded. This is the code for selecting a folder.
Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
TextBox1.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub
Now I just need to know how to take directory that appears in the textbox and have the file get downloaded to there. Here is the code for the download.
My.Computer.Network.DownloadFile("http://download1516.mediafire.com/wtzr4h1b37zg/ptzcffq933e87c8/sword_custom.png", "C:\Users\Administrator")
What would I need to replace "C:\Users\Administrator" with?
Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
Dim URL As String = "http://download1516.mediafire.com/wtzr4h1b37zg/ptzcffq933e87c8/sword_custom.png"
Dim SaveFile As String = "sword_custom.png"
With FolderBrowserDialog1
If .ShowDialog = DialogResult.OK Then
TextBox1.Text = .SelectedPath
My.Computer.Network.DownloadFile(URL, IO.Path.Combine(.SelectedPath, SaveFile))
End If
End With
End Sub

Creating text files not working

This is probably a question that many of you have already seen a couple of times, but I'm really desperate since every solution i find on the internet doesn't work properly.
I want to create a simple .txt file. My code atm:
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MessageBox.Show("Your world needs a name")
Else
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
End If
End Sub
End Class
So as you can see, a file should be created when the button is pressed AND when there is text in the textbox.
Is the program not working or am searching the file in the wrong place? Thanks in avance!
Something like this may also be used:
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MessageBox.Show("Your world needs a name")
Else
Using file As New StreamWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
End Using
End If
End Sub
End Class
Try this code
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MessageBox.Show("Your world needs a name")
Else
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "test.txt"), True)
file.WriteLine("Here is the first string.")
file.Close()
End If
End Sub

Combobox moving resources to disk

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedText = "Anaheim" Then Dim finalpath As String = "C:\hockey055f\data\model\ice0.png"
My.Resources.anaice.Save("C:\hockey055f\data\model\ice0.png")
MsgBox("Installed!", MsgBoxStyle.Information, "Installed by GoLeafsGo")
ElseIf ComboBox1.SelectedText = "Boston" Then If System.IO.File.Exists("c:\hockey055f\data\model\ice0.png") Then
System.IO.File.Delete("c:\hockey055f\data\model\ice0.png")
My.Resources.bosice.Save("C:\hockey055f\data\model\ice0.png")
MsgBox("Installed!", MsgBoxStyle.Information, "Installed by GoLeafsGo")
End Sub
This is my code. I am trying to make it so that when an item is selected by the user in the combobox and the user presses the button, the file will transfer from my resources to the directory shown above. When I click on the first value (Anaheim), the file "anaice.png" is transferred, but then the "bosice.png" from the (Boston) value is put in and overwrites the the other image. Help please!
Try this, But I don't know if this is what you want:
private finalpath As String = "C:\hockey055f\data\model\ice0.png"
private res = nothing
private sub ComboBox_Selectedindexchanged(sender As Object, e As EventArgs) _
handles ComboBox1.Selectedindexchanged
Select case sender.Selectedindex
case is 0:res= My.Resources.anaice
case is 1:res= My.Resources.bosice
case else
msgbox ("select case is out of range")
end select
end sub
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
try:io.File.Delete(finalpath):catch:end try
res.Save(finalpath)
MsgBox("Installed!", MsgBoxStyle.Information, "Installed by GoLeafsGo")
End Sub
PS: Code is written on the fly maybe it contains syntax error(s).