Copying a file from a directory to another one - vb.net

I have a an application which is supposed to copy a selected file whose directory is written in txtbox1 to a folder of director written in txtbox2 as follows :
code :
Dim sourcepath As String = TextBox1.Text
Dim DestPath As String = TextBox2.Text
CopyDirectory(sourcepath, DestPath)
Called sub:
Private Shared Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
For Each folder As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
CopyDirectory(folder, dest)
Next
End Sub
This code copies all the files, not the specified one only. Can someone please tell me how to make this sub copy only the selected file not all the files in the folder?

You're taking the entire path as an argument (something like this: C:/someDirectory/filename.txt) and aren't comparing the filename to the other filenames in that directory.
Instead of using:
For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
Try:
Dim sourceFileName = Path.GetFileName(sourcePath)
For Each filePath As String in Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim filename As String = Path.GetFileName(filePath)
If sourceFileName = filename
'Do your copy code here
End If
Next

Related

GetFiles is incredibly slow vb.NET

I need to process a large amount of files and scour thru a group of directories and subdirectories and get the file from the found directory. This is easy using a simple directory but when scouring a thousand directories, the program slows down to a crawl. I've heard of using enumeratefiles but I'm not how to approach this. thank you.
How should I approach this?
dim Filename_to_lookfor as string
dim filePaths As String()
for i = 0 to 1000
Filename_to_lookfor = array(i)
filePaths = Directory.GetFiles(sTargetPath, sFilename_to_lookfor.ToUpper,
IO.SearchOption.AllDirectories)
if filepath.length > 0 then
'copy file using Computer.FileSystem.CopyFile()
end if
next
Thank you.
Another coding would be using Linq:
Sub SearchFiles(pathAndfileNames_to_lookfor() As String, sTargetPath As String)
' Call just once Directory.GetFiles():
Dim FilePaths() As String = Directory.GetFiles(sTargetPath, "*.*", IO.SearchOption.AllDirectories)
Dim lookup1 = FilePaths.ToLookup(Function(x) x.ToLower)
Dim lookup2 = pathAndfileNames_to_lookfor.ToLookup(Function(x) x.ToLower)
Dim filesInBoth = lookup1.SelectMany(Function(x) x.Take(lookup2(x.Key).Count).ToArray)
For Each file In filesInBoth
'copy file using Computer.FileSystem.CopyFile()
Console.WriteLine(file)
Next
End Sub
Calling the procedure would be as follows:
Dim file1 As String = "C:\...\file1..."
Dim file2 As String = "C:\...\file2..."
Dim pathAndfileNames_to_lookfor() As String = New String() {file1, file2}
Dim sTargetPath = "..."
SearchFiles(pathAndfileNames_to_lookfor, sTargetPath)

Need to strip numbers out of a filename string to change save location

I'm having an issue where I need to strip a filename from a path but can't quite figure out the code.
An example filename would be C:\Checked out parts\001-1099-01.slddrw. I need to extract the "001-1099-01." portion. The file location to the left could be anything and the only constants in the file name are the "001-" portion (which I should point out, could repeat if the filename was 001-1001-03) and the ".slddrw". Other than that the filename could be named "001-10999-03-02-01".
I have stripped out the slddrw portion easily, I tried using Right and InStr functions to strip the rest off but I think that InStr only works with letters (couldn't find any number examples anyways)
I believe this is what you are looking for:
Public Sub test()
Dim strFileName As String
'Your sample file name
strFileName = "C:\Checked out parts\001-1099-01.slddrw"
'Search for the first occurance of \ in the reversed (!) file name
' if you substract this result from the length of the string
' you know where to start (+ 2 to avoid the \ itself)
strFileName = Mid(strFileName, Len(strFileName) - InStr(1, StrReverse(strFileName), "\") + 2)
'Remove the .slddrw portion from the end
strFileName = Replace(strFileName, ".slddrw", "")
'Done
Debug.Print strFileName
End Sub
Note the comments in the code for more information.
You can use a sub in which you define the path and extension of your file and it will give you the filename.
Sub getFileName()
Dim myString() As String
Dim path As String, extension As String
Dim fileName As String
path = "C:\Checked out parts\"
extension = ".slddrw"
'Say your string is in cell A1
myString = Split(Range("A1"), path)
fileName = Split(myString(1), extension)(0)
MsgBox fileName 'fileName can be used elsewhere after
End Sub
You could also do it as a function:
Function getFileName(cel As Range, path As String, extension As String)
Dim myString() As String
myString = Split(cel, path)
getFileName = Split(myString(1), extension)(0)
End Function
If you have the path and extensions stored in cells, you can use this function:
Function getFileName2(cel As Range, path As Range, extension As Range)
Dim myString() As String
myString = Split(cel, path)
getFileName2 = Split(myString(1), extension)(0)
End Function
Those are the options I can think of, hope it helps.
EDIT:
If you don't know the path nor the extension, you can use this instead:
myString = Split(Range("A1"), "\")
fileName = Split(myString(UBound(myString)), ".")(0)

Renaming all files in a folder

I'm wondering if it's possible to rename all the files in a folder with a simple program, using vb.NET
I'm quite green and not sure if this is even possible.
Lets say there is a folder containing the files:
Text_Space_aliens.txt, fishing_and_hunting_racoons.txt and mapple.txt.
Using a few credentials:
Dim outPut as String = "TextFile_"
Dim fileType as String = ".txt"
Dim numberOfFiles = My.Computer.FileSystem.GetFiles(LocationFolder.Text)
Dim filesTotal As Integer = CStr(numberOfFiles.Count)
Will it be possible to rename these, regardless of previous name, example:
TextFile_1.txt, TextFile_2.txt & TextFile_3.txt
in one operation?
I think this should do the trick. Use Directory.GetFiles(..) to look for specific files. Enumerate results with a for..each and move (aka rename) files to new name. You will have to adjust sourcePath and searchPattern to work for you.
Private Sub renameFilesInFolder()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim i As Integer = 0
For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
In your title you state something about chronologically, but within your question you never mentioned it again. So I did another example ordering files by creationTime.
Private Sub renameFilesInFolderChronologically()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
I've never done Lambdas in VB.net but tested my code and it worked as intended. If anything goes wrong please let me know.

Files in directory sort by fileName ascending - for each

How to update my code so that all files are processed in order of date/time created?
Private Sub StartupFindExistingFiles(Path As String, SearchPattern As String)
Dim fileEntries As String() = Directory.GetFiles(Path, SearchPattern)
For Each fileName As String In fileEntries
PrintJOBFile(fileName)
Next
End Sub
You could use LINQ with File.GetCreationTime:
Dim orderedByCreation = From file In Directory.EnumerateFiles(Path, SearchPattern)
Let createdAt = System.IO.File.GetCreationTime(file)
Order By createdAt Ascending
Select file
For Each filePath As String In orderedByCreation
PrintJOBFile(filePath)
Next
Note that you could also use GetFiles instead of EnumerateFiles. The latter can be more efficient.

Copy subfolders to another folder in VB.NET without overwriting

I have this code which I am using to copy a directory:
Private Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
For Each file1 As String In Directory.GetFiles(sourcePath)
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file1))
File.Copy(file1, dest)
Next
For Each dir1 As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
Dim destdir As String = Path.Combine(destPath, Path.GetFileName(dir1))
CopyDirectory(dir1, destdir)
Next
End Sub
And this is how I call CopyDirectory method:
Dim sourcepath As String = "E:\Crazy\"
Dim DestPath As String = "D:\Snippets\"
CopyDirectory(sourcepath, DestPath,)
The problem is that it continously copies the folder again and again. How do I stop this? And how do I copy the subfolder a single time? I have used recursion.
Your problem lies here:
For Each dir1 As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
This will get the parent folder of the destPath, not the correct path to copy from.
Also, you have a problem with File.Copy. If the file already exist in the destination path, calling File.Copy without an explict request to overwrite the destination will throw an exception.
Private Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
For Each file1 As String In Directory.GetFiles(sourcePath)
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file1))
File.Copy(file1, dest, True) ' Added True here to force the an overwrite
Next
' Use directly the sourcePath passed in, not the parent of that path
For Each dir1 As String In Directory.GetDirectories(sourcePath)
Dim destdir As String = Path.Combine(destPath, Path.GetFileName(dir1))
CopyDirectory(dir1, destdir)
Next
End Sub