CopyFile isn't copying my file with the same extension? - vb.net

I am trying to make it so my user can copy files from one folder to another folder, their playlist folder, so that they can use it throughout my program. So I tried this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim result As DialogResult = MessageBox.Show("Are you sure you want to finish the playlist?", "Finish Playlist- WikiFinder", MessageBoxButtons.YesNo)
If (result = DialogResult.Yes) Then
For Each Item In ListBox1.Items
Dim str As String = IO.Path.Combine(MusicMenu.FolderBrowserDialog2.SelectedPath, "DONUTS")
My.Computer.FileSystem.CopyFile(Item.ToString(), str)
Next
Else
End If
End Sub
This works and makes the file, but the issue is I told it to copy an MP3 file and it just gave me a "File". Is there any way I can copy the file AND keep the original file's extension?

Since you pass only the directory to the CopyFile function, it creates a FILE.
Pass filename with Extension.
For Each Item In ListBox1.Items
Dim str As String = IO.Path.Combine(MusicMenu.FolderBrowserDialog2.SelectedPath, "DONUTS")
str = IO.Path.Combine(str,IO.Path.GetFileName(Item.ToString()))
My.Computer.FileSystem.CopyFile(Item.ToString(), str)
Next
Now the files will be copied to your DONUTS folder.

Related

How can I move a certain file extension into one folder with VB

I am new to VB and would like to create a software that moves a certain file extension into a single folder. I have already built the code that creates a folder on the desktop when clicking the button although after that runs I need to compile a certain file such as (.png) into the folder in created.
This code creates two buttons that when pressed creates a folder called "Pictures" and "Shortcuts".
How would I go about moving all .png files from the desktop into the pictures folder?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Pictures")
MessageBox.Show("Pictures Compiled And Cleaned")
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Shortcuts")
MessageBox.Show("Shortcuts Compiled And Cleaned")
End Sub
End Class
We'll start simple. This command will generate an array of all the PNG files' paths on the desktop
Dim filePaths = Io.Directory.GetFiles("C:\Users\bj\Desktop\", "*.png")
We can loop through this array and act on each filepath:
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
We have to pull the filename off the path and put it into a new path, then move from old to new. This I also how you rename files; have a new name in the same folder and use Move. Always use the Path class to cut and combine file paths

Delete Many Files In Application Data Folder

I'm trying to delete 3 files (file1.sol file2.sol file3.sol)
from the Application Data folder. My code words just fine with one file, but how can I make it delete the three files?
Here is my code:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Dim fileList As New List(Of String)
GetAllAccessibleFiles(path, fileList)
Application.DoEvents()
Dim files As String() = fileList.ToArray
For Each s As String In fileList
My.Computer.FileSystem.DeleteFile(s)
Next
End Sub
Sub GetAllAccessibleFiles(ByVal path As String, ByVal filelist As List(Of String))
For Each file As String In Directory.GetFiles(path, "file1.sol")
filelist.Add(file)
Next
For Each file As String In Directory.GetFiles(path, "file2.sol")
filelist.Add(file)
Next
For Each file As String In Directory.GetFiles(path, "file3.sol")
filelist.Add(file)
Next
For Each dir As String In Directory.GetDirectories(path)
Try
GetAllAccessibleFiles(dir, filelist)
Catch ex As Exception
End Try
Next
End Sub
The first line in GetAllAccesibleFiles, is searching for files with the name: "file1.sol", that means it will only retrieve that file. Try "file*.sol" meaning it starts with "file" and ends with ".sol". That should work. If you only want to delete file1 ,2 ,and 3, not for example, file4, then you can run a for loop 3 times, check if "file1" exists, delete it, check if "file2" exists, and so on.

copy folder path to listbox

I manage to drag and drop multiple folder path to listbox, is it possible to do this using copy/paste, for example, you copy multiple folder on windows explorer then paste those folder path on the listbox using contextmenu, shortcut keys, or a button..
Private Sub lstFolder_DragDrop(sender As Object, e As Windows.Forms.DragEventArgs) Handles lstFolder.DragDrop
Dim directories As String() = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())
For Each folder As String In From folders In directories Where Directory.Exists(folders)
If Not lstFolder.Items.Contains(folder.ToString()) Then
lstFolder.Items.Add(folder.ToString())
End If
Next
End Sub
Private Shared Sub lstFolder_DragEnter(sender As Object, e As Windows.Forms.DragEventArgs) Handles lstFolder.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
# Vignesh Kumar
works great, one question how about, copying the folder location from a document file or from address bar, here is my code so far.
Dim directories As String() = CType(Clipboard.GetData(Windows.Forms.DataFormats.FileDrop), String())
'loop through the string array, check if folder exist then adding each folder to the ListBox
For Each folder As String In From folders In directories Where Directory.Exists(folders)
If Not lstFolder.Items.Contains(folder.ToString()) Then
lstFolder.Items.Add(folder.ToString())
End If
Next
Yes. Use Clipboard object
string[] files = (string[])Clipboard.GetData(System.Windows.Forms.DataFormats.FileDrop);
Files or/and folders will be in this string array.

Creating an application that moves a collection files from one place to another using VB

So this is an application I have to create that moves files from one directory to another, both directories being specified by the user. It seems easy enough, but the problem is that there are millions of files that have to be searched through. These files are all named with 8 digits for example, "98938495.crt". The directory where all these files are has multiple folders. These folders within the main one are named with the first two digits of all the files that are in the folder. And then in that folder there are roughly ten zipped folders that contain 100,000 files each. The name of those folders are the minimum and maximum names of the files. For example, I go into the main folder, then click on the "90xx" folder. In that one there are 10 zipped folders which are named with the minimum and maximum names of the files, like "90000000_90099999.zip". That zip folder contains 100000 files. Now, this app is supposed to find all the files that the user inputs and then move them to a folder specified by the user. I have posted my code so far below, any help at all is greatly appreciate!!
FYI: The STID is the name of the file.
GUI for the app
Edit: I realized there is no way to answer this question because there really isn't a question, just a broken app. Basically, how do i search for the items in the directory and then copy them into a new directory?
Imports System
Imports System.IO
Public Class CertFinder
Private Sub SourceDirectoryTB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SourceDirectoryTB.TextChanged
End Sub
Private Sub DestinationDirectoryTB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DestinationDirectoryTB.TextChanged
End Sub
Private Sub SearchTB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchTB.TextChanged
End Sub
Private Sub SourceButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SourceButton.Click
Dim fbd As New FolderBrowserDialog
fbd.RootFolder = Environment.SpecialFolder.MyComputer
If fbd.ShowDialog = DialogResult.OK Then
SourceDirectoryTB.Text = fbd.SelectedPath
End If
End Sub
Private Sub DestinationButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DestinationButton.Click
Dim fbd As New FolderBrowserDialog
fbd.RootFolder = Environment.SpecialFolder.MyComputer
If fbd.ShowDialog = DialogResult.OK Then
DestinationDirectoryTB.Text = fbd.SelectedPath
End If
End Sub
Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchButton.Click
'Array of stids
Dim stidsToFind As String()
'get text in the searchTB textbox
Dim searchTBText As String = Me.SearchTB.Text.Trim()
'splits stids into seperate lines
stidsToFind = searchTBText.Split(vbCrLf)
'gets text from source directory text box
Dim sourceDirectory As String = Me.SourceDirectoryTB.Text.Trim()
'gets text from destination directory text box
Dim destinationDirectory As String = Me.DestinationDirectoryTB.Text.Trim()
Dim fullPathToFile As String = sourceDirectory
'Go through each stid in the search text box and continue if nothing
For Each stidToFind As String In stidsToFind
If String.IsNullOrWhiteSpace(stidToFind) Then
Continue For
End If
'Find the first two digits of the stid
Dim firstTwoDigitsOfSTID As String = stidToFind.Substring(0, 2)
'In the specified directory, find the folder with the first two digits and "xx"
fullPathToFile = fullPathToFile & "\" & firstTwoDigitsOfSTID & "xx"
Dim allFileNames As String() = Nothing
allFileNames = Directory.GetFiles(sourceDirectory, "*.crt*", SearchOption.AllDirectories)
Next
'-------------------------------------------------------------------------------
Try
If File.Exists(fullPathToFile) = False Then
Dim FS As FileStream = File.Create(fullPathToFile)
FS.Close()
End If
File.Move(fullPathToFile, destinationDirectory)
Console.WriteLine("{0} moved to {1}", fullPathToFile, destinationDirectory)
Catch ex As Exception
MessageBox.Show("File does not exist")
End Try
Dim sc As New Shell32.Shell()
'Declare the folder where the files will be extracted
Dim output As Shell32.Folder = sc.NameSpace(destinationDirectory)
'Declare your input zip file as folder .
Dim input As Shell32.Folder = sc.NameSpace(stidsToFind)
'Extract the files from the zip file using the CopyHere command .
output.CopyHere(input.Items, 4)
'-------------------------------------------------------------------------------
' 1. Get the names of each .zip file in the folder.
' 2. Assume that the .zip files are named as such <minimum STID>_<maximum STID>.zip
' 3. For each .zip file name, get the Minimum STID and Maximum STID values.
' 4. Check the range of 'stidToFind' against the STID ranges of each .zip file.
' 5. Once the .zip file is located,
' a. Copy the .zip file to the local computer OR
' b. Just leave it where it is.
' 6. Unzip the file.
' 7. Create the full file name path. ../<stidToFind>.crt
' 8. Copy the file to the destination directory.
' 9. Delete the unzipped folder
' 10. Delete the .zip file (IF you've copied it to your local computer).
End Sub
End Class
In answer to the .ZIP unpacking, use the System.IO.Packaging (more can be found at CodeProject - Zip Files Easy)
Don't you think using a database would be easier to store that data?

VB - cannot copy file due to "being used by another process" error

I haven't been able to pinpoint exactly what is causing this error. All im trying to do is copy files (pdfs) that were created on the current day from 1 directory to another after a certain amount of time with the ticker. Here is my code:
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
Dim file As String
Dim now As String = DateTime.Today.ToShortDateString
Dim dir As String = "C:\PDFs\"
Dim bupdir As String = "C:\PDFs\copied\"
Dim Files() As String = Directory.GetFiles(dir)
For Each file In Files
Dim dt As String = IO.File.GetLastWriteTime(file).ToShortDateString
If dt = now Then
IO.File.Copy(Path.Combine(dir, file), Path.Combine(bupdir, file), True)
End If
Next
End Sub
Your problem lies in the fact that Directory.GetFiles() returns the full path name of the files in the source directory.
Then, when you try to build the destination file name, the Path.Combine sees that your file variable is an absolute path and doesn't add the path bupdir.
This gives back the value of the variable file and you end up with something like this
IO.File.Copy("C:\PDFs\file.pdf", "C:\PDFs\file.pdf", True)
To fix the problem
IO.File.Copy(file, Path.Combine(bupdir, Path.GetFileName(file)), True)
FROM MSDN
If one of the specified paths is a zero-length string, this method
returns the other path. If path2 contains an absolute path, this
method returns path2.