Directory.GetFiles Method Not Working In VB - vb.net

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

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

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

opening files added to a combobox

Dim dir = "..//Football/"
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(dir)
FfilesComboBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file))
Next
End Sub
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
Dim openfile As String = System.IO.Path.Combine(dir, FfilesComboBox.SelectedItem.ToString)
'start the process using the openfile string
Process.Start(openfile)
End Sub
I am able to add all the files to combobox but the problem is i cannot open the file when selected from the combobox
Try this
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(dir)
FfilesComboBox.DisplayMember = "key"
FfilesComboBox.ValueMember = "value"
FfilesComboBox.Items.Add(New DictionaryEntry(System.IO.Path.GetFileNameWithoutExtension(file), System.IO.Path.GetFileName(file)))
Next
End Sub
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
Dim openfile As String = System.IO.Path.Combine(dir, FfilesComboBox.SelectedItem.Value.ToString)
'start the process using the openfile string
Process.Start(openfile)
End Sub
If you Then use Visual studio 2008 or newer. you can use Anonymous class to store the full file path with the FileNameWithoutExtension.
Dim dir = "..//Football/"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FfilesComboBox.DisplayMember = "Text"
End Sub
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(Dir)
FfilesComboBox.Items.Add(New With {.Text = System.IO.Path.GetFileNameWithoutExtension(file), .Value = file})
Next
End Sub
you can use ComboBox1.SelectedItem.Value to get the value (that is the file full path)
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
'start the process using the openfile string
Process.Start(FfilesComboBox.SelectedItem.Value)
End Sub
This will work even you choose to loop over sub directories.
This code is tested and worked fine

Open a ".exe" with a Button using a file path from a TextBox

I have a TextBox called TextBox1, which is filled by a Button that gets a file path using OpenFileDialog. I want a button (Button3) to start several processes one after another with an interval of 2 hours then close it and open the next one.
In total I have 4 different TextBoxes (TextBox1, TextBox2, TextBox3 and TextBox4) and 4 different file paths that I want to open with the same button with the interval I mentioned before.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:temp"
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox1.Text = OpenFileDialog1.FileName.ToString()
If Not (strm Is Nothing) Then
'insert code to read the file data
strm.Close()
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
OpenFileDialog2.Title = "Please Select a File"
OpenFileDialog2.InitialDirectory = "C:temp"
OpenFileDialog2.ShowDialog()
End Sub
Private Sub OpenFileDialog2_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog2.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog2.OpenFile()
TextBox3.Text = OpenFileDialog2.FileName.ToString()
If Not (strm Is Nothing) Then
'insert code to read the file data
strm.Close()
End If
End Sub
Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
End Sub
End Class
To launch a new process use:
dim myProcess = Process.start(filename)
You dont' need the code that does the following:
Dim strm As System.IO.Stream
strm = OpenFileDialog2.OpenFile()
If Not (strm Is Nothing) Then
strm.Close()
End If
This is opening the exe file as if it were trying to read the data from it.
Instead just use
dim process = Process.Start(OpenFileDialogX.Filename)
Note: your initial directory seems to be c:temp not c:\temp as it probably should be

How do I store a text file inside a VB.net project?

I have built a basic VB app in the latest visual studio community. It's a simple app to load a text file into a list box then allow the list to be filtered down and finally the selected value to be copied.
It all works fine but I am curious, if I want to distribute this to other users I need to send them the text file (and the location is currently hard coded).
There has to be a better way to do this, do I need to import the text file as some sort of object in my project so it is then part of the project as opposed to a text file on its own?
Here is my code:
Public Class Form1
Dim MyArray() As String = My.Computer.FileSystem.ReadAllText("C:\Temp\Products.txt").Split(Environment.NewLine)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.DataSource = MyArray
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox2.Text = ListBox1.SelectedValue
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Clipboard.Clear()
Clipboard.SetText(TextBox2.Text)
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim FilteredArray(0) As String
Dim ProdName As String
Dim X As Long = 0
ListBox1.DataSource = MyArray
For Each ProdName In ListBox1.Items
If InStr(UCase(ProdName), UCase(TextBox1.Text)) > 0 Then
ReDim Preserve FilteredArray(X)
FilteredArray(X) = ProdName
X = X + 1
End If
Next
ListBox1.DataSource = FilteredArray
End Sub
End Class
Any help is appreciated.
For completeness, here is my final solution:
Imports System.IO
Imports System.Reflection
Public Class Form1
Dim MyArray() As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using sr As StreamReader = New StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("WindowsApplication2.Products.txt"))
MyArray = Split(sr.ReadToEnd(), vbLf)
End Using
ListBox1.DataSource = MyArray
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox2.Text = ListBox1.SelectedValue
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Clipboard.Clear()
Clipboard.SetText(TextBox2.Text)
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim FilteredArray(0) As String
Dim ProdName As String
Dim X As Long = 0
ListBox1.DataSource = MyArray
For Each ProdName In ListBox1.Items
If InStr(UCase(ProdName), UCase(TextBox1.Text)) > 0 Then
ReDim Preserve FilteredArray(X)
FilteredArray(X) = ProdName
X = X + 1
End If
Next
ListBox1.DataSource = FilteredArray
End Sub
End Class
I think is a good way to store such file is resources of assembly.
Include your file into project. Set Build Action to Embedded Resource and then this file will be store inside the assembly.
How to read resource file from assembly you can find here: How to read embedded resource text file