I would like to move the folder and its contents to another directory. This means the folder and contents will no longer exist from the source and will be moved to its destination. But when the destination path has the same folder name, it will just overwrite the folder and its content.
I'm getting error if same folder exists in the destination path using the code below.
The catch here is I don't exactly know the folder name and filename here inside the source path. I just know where I'm going to get the folder and files to move to its destination.
I've used these codes but couldn't figure out how to overwrite:
'web.config
Sourcepath = "C:\TestSource\"
Destinationpath = "C:TestDestiation\"
'calling the move function:
dInfoSource = New DirectoryInfo(ccConfigClass.SourcePath)
dInfoDestination = New DirectoryInfo(ccConfigClass.DestinationPath)
MoveContents(dInfoSource, dInfoDestination)
Public Sub MoveContents(sourcePath As DirectoryInfo, destinationPath As DirectoryInfo)
Try
If (Not destinationPath.Exists) Then
destinationPath.Create()
End If
'Move all Files
For Each file As FileInfo In sourcePath.GetFiles()
file.MoveTo(Path.Combine(destinationPath.FullName, file.Name))
Next
'Move all folders
For Each dir As DirectoryInfo In sourcePath.GetDirectories()
dir.MoveTo(Path.Combine(destinationPath.FullName, dir.Name))
Next
Catch ex As Exception
Dim objErrorLogger As New ErrorLogging
objErrorLogger.LogError(_CLASS_NAME, Reflection.MethodInfo.GetCurrentMethod.Name, ex.Message.ToString, ex)
End Try
End Sub
Related
i have three folder in "D:\TestField". These are "backups","ExampleFileUpdatePrimary","ExampleFileUpdateSecondary.zip". I can delete "D:\TestField\ExampleFileUpdatePrimary" folder ,but i cant delete "D:\TestField\ExampleFileUpdateSecondary.zip"
my sub function is ;
Private Sub DeleteFolder(ByVal path As String)
path = path.Remove(path.Length - 1) 'D:\TestField\ExampleFileUpdatePrimary
Dim path2 = path & ".zip" 'D:\TestField\ExampleFileUpdateSecondary.zip
My.Computer.FileSystem.DeleteDirectory(path, FileIO.DeleteDirectoryOption.DeleteAllContents) 'its working
'Dim di = New IO.DirectoryInfo(path2) 'try1
'di.Delete(True)
'IO.Directory.Delete(path2) 'try2
'My.Computer.FileSystem.DeleteDirectory(path2, FileIO.DeleteDirectoryOption.DeleteAllContents) 'try3
End Sub
try1,try2 exceptions says " The directory name is invalid"
try3 exception says "System.IO.DirectoryNotFoundException: ''D:\TestField\ExampleFileUpdateSecondary.zip "
i couldnot find a new solution or try to delete a .zip file in code
thanks
Directory entries ending on .zip are usually files not folders, even though Windows Explorer displays them as folders.
Since they are files, use File.Delete instead.
I'm fairly familiar with bash, but I'm very, ***very**** new to vb.net. I'm searching for an easy way to find files in a folder that end with .G1, .G2, .G3, etc. but NOT .GP1, .GP2, .GP3, etc. Then for each file I need to copy it to another folder using a different file name but the same extension. I've managed to figure this out for the unique files, but there will be an undefined number of these depending on the project and I need to make sure that I get them all. Hard coding is possible, but very, very ugly. Any suggestions?
Here's the remnants of a failed attempt:
Public Sub FindGFiles()
FileList = IO.Directory.GetFiles(searchDir, ".G[1-99]" + , IO.SearchOption.AllDirectories)
For Each foundfile As String In FileList
If foundfile.Contains(".G#") Then
'copy file somehow and retain file extension
Else
MsgBox("No match")
End If
Next
End Sub
The GetFiles-method does only support * and ? wildcard characters.
So you have to get all files with a *.G*-extension first.
In the For Each-loop one can then use the Like-operator to check the desired pattern:
Public Sub CopyGFiles(searchDir As String, destDir As String)
Dim fileList As String() = IO.Directory.GetFiles(searchDir, "*.G*", IO.SearchOption.AllDirectories)
Dim fileName As String
Dim extension As String
For Each foundfile As String In fileList
fileName = IO.Path.GetFileNameWithoutExtension(foundfile)
extension = IO.Path.GetExtension(foundfile)
If extension Like ".G#" OrElse
extension Like ".G##" Then
'copy file to destination, append "_new" to the filename and retain file extension
IO.File.Copy(foundfile, IO.Path.Combine(destDir, fileName & "_new" & extension))
Else
'pattern not matched
End If
Next
End Sub
The method-call would then be as follows:
CopyGFiles("C:\Temp", "C:\Temp\Dest")
This should be done inside a Try/Catch as different exceptions can occur when working with files.
Try
CopyGFiles("C:\Temp", "C:\Temp\Dest")
Catch ex As Exception
MessageBox.Show("An error occured" + vbCrLf + ex.Message)
End Try
I want to move multiple files from one directoy to anoher. I use 'My.Computer.FileSystem.MoveFile' and that works fine but it handles one file at a time. So, for every already existing file in that directory I get a warning (ie. 'File already exists') instead of one warning for the batch. Is it posible to get one warning for all the moved files?
For i = .Items.Count - 1 To 0 Step -1
Dim map = .Items.Item(i).SubItems(COL_MAP).Text
Dim bestandHernoemd = .Items.Item(i).SubItems(COL_HERNOEMD).Text
Dim bestandOrigineel = .Items.Item(i).SubItems(COL_ORIGINEEL).Text
Try
My.Computer.FileSystem.MoveFile(map & bestandOrigineel, My.Settings.OPTIE_OvernemenStandaardMapNaam & bestandHernoemd, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException)
.Items.RemoveAt(i)
Catch ex As Exception
foutLijst.Add(bestandOrigineel & ": " & ex.Message)
End Try
Next
And if you want to copy files recursively ( all folders, subfolders, files or subfiles ) from one source to destination, you can use the below sub procedure. No Warning applied and shall overwrite the destination.
Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)
'If the destination folder doesn't exist then create it'
If Not System.IO.Directory.Exists(destinationPath) Then
'Obs, folder doesn't exist, create one please :)'
System.IO.Directory.CreateDirectory(destinationPath)
End If
Dim fileSystemInfo As System.IO.FileSystemInfo
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
Dim destinationFileName As String = System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)
'Now check whether its a file or a folder and take action accordingly
If TypeOf fileSystemInfo Is System.IO.FileInfo Then
System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
Else
' Recursively call the method to copy all the nested folders
CopyDirectory(fileSystemInfo.FullName, destinationFileName)
End If
Next
End Sub
I want to move all files and folders from current directory to another directory excluding a folder named "My Folder". I want to know how can I do this with vb?
Not really tested but might be helpful anyway:
Dim currentDir = Directory.GetCurrentDirectory() ' or whatever you call current
Dim targetDir = Path.Combine(currentDir, "Target-Directory")
Directory.CreateDirectory(targetDir)
Dim allDirs = From dir In Directory.EnumerateDirectories(currentDir, "*.*", SearchOption.AllDirectories)
Where Not Path.GetFileName(dir).Equals("My Folder", StringComparison.InvariantCultureIgnoreCase)
For Each dir As String In allDirs
Try
Dim targetPath As String = Path.Combine(targetDir, Path.GetFileName(dir))
Directory.Move(dir, targetPath)
Catch ex As Exception
' log or whatever, here just ignore and continue ...
End Try
Next
'now move the rest of the files in the troot folder
Dim filesInRoot = From file In Directory.EnumerateFiles(currentDir, "*.*", SearchOption.TopDirectoryOnly)
For Each file As String In filesInRoot
Try
Dim targetPath As String = Path.Combine(targetDir, Path.GetFileName(file))
IO.File.Move(file, targetPath)
Catch ex As Exception
' log or whatever, here just ignore and continue ...
End Try
Next
I have a folder called test which has subfolders: A, B, and C at the root. I am trying to copy a file to these three folders.
Not sure why the I am getting the error:
The target file "c:\test\A" is a directory and not a file. Please help.
Dim OPUSINI As New FileInfo("C:\Program Files (x86)\OPUS_4.5\OPUS32.INI")
'Where is will be going
'Dim Win7DestLocation As String = "C:\Users"
Dim Win7DestLocation As String = "C:\test"
Dim WinXPDestLocation As String = "C:\Documents and Settings"
'Get a list of all the Subfolders within the Destination location
Dim Win7Destdir As New DirectoryInfo(Win7DestLocation)
Dim WinXPDestdir As New DirectoryInfo(WinXPDestLocation)
'Checks if Destination Exists for Windows 7
Dim Win7CheckExistDestLocation As New IO.DirectoryInfo(Win7DestLocation)
'Checks if Destination Exists for Windows XP
Dim WinXPCheckExistDestLocation As New IO.DirectoryInfo(WinXPDestLocation)
If Win7CheckExistDestLocation.Exists Then
Try
For Each subfolder As DirectoryInfo In Win7Destdir.GetDirectories
OPUSINI.CopyTo(subfolder.FullName, True)
Next
Catch ex As Exception
MessageBox.Show("Unable to backup Pump data files." + ex.ToString, "Backup Error:", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
You are passing a directory name to CopyTo.
That method wants a filename not a directory name.
Thus the exception received.
If I understand your code well, you need to change that line to
Dim destFile = Path.Combine(subfolder.FullName, OPUSINI.Name))
OPUSINI.CopyTo(destFile, True)
Also using DirectoryInfo objects is not really necessary here.
The simple Directory class could do the same things with less overhead