VB NET - CopyDirectory only copies files? Why? - vb.net

I have been trying to do this seemingly simple task for a while now, but no luck. Here is some pieces of code I'm using...
Dim SDPath As String = TextBox1.Text
Dim ContentPath As String = TextBox2.Text
Dim RPXName As String = TextBox4.Text
Dim Copy_To_Dir As String = SDPath & RPXName
Dim Copy_To_Dir As String = SDPath & RPXName
'copy any subdirs from ContentDir to SD:\RPXName
For Each ContentDirSub In System.IO.Directory.GetDirectories(ContentPath, "*", IO.SearchOption.AllDirectories)
My.Computer.FileSystem.CopyDirectory(ContentDirSub, Copy_To_Dir, True)
Next
This should create the sub directories in the specific path. Where am I going wrong here??? I've been scouring examples but found nothing. I also want this to copy the contents of the sub directory as well.

Not sure why it isn't working but you could try to make sure that the path you are copying to is a correct directory path. The below code combines the path into a correct path name.
Dim Copy_To_Dir As String = System.IO.Path.Combine(SDPath & RPXName)
You also don't need to write that twice.
Is there any errors appearing?

Related

Delete A File That Contains The App Name (VB.NET)

This is the code I'm Using:
Dim file As String
Dim prefetchPath As String
Dim FileName As String = My.Application.Info.AssemblyName
prefetchPath = Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine) & "\Prefetch"
For Each file In IO.Directory.GetFiles(prefetchPath)
If file.Contains(FileName) Then
IO.File.Delete(file)
End If
Next
i don't know why it does not work if i use FileName. But it work if i use this code
If file.Contains("Example.exe") Then
IO.File.Delete(file)
End If
I want to make sure that if someone changes the name of the application the code works the same way(I already running the file as Administrator)
Help me Thanks.
My guess is that AssemblyName only returns the name without the extension, try including the .exe. Also, it is worth noting that you can use the IO.DirectoryInfo class and pass the file name in the GetFiles method to cut out your For/Each loop.
Here is a quick example:
Dim prefetchPath As String = IO.Path.Combine(Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine), "Prefetch")
Dim FileName As String = My.Application.Info.AssemblyName & ".exe"
If New IO.DirectoryInfo(prefetchPath).GetFiles(FileName).Count > 0 Then
IO.File.Delete(IO.Path.Combine(prefetchPath, FileName))
End If

Comparing files in list of string to files in target directory

I have searched this issue for 2 days, without finding a solution. I might be using the wrong search terms, due to my limited knowledge of the subject.
I have 2 folders, a source and a target, each with files in them. I need to compare the files in these 2 dirs and delete the duplicate files from the target dir before moving the files from the source dir.
I have created a list of string for both dirs. But I can't seem to figure out how to make the dupes in the targetdir to get deleted instead of from the list itself. However, if I put targetdir or sourcedir in the File.Exists() and File.Delete(), it doesn't see the files.
My code is below. Can anyone help me with this?
Dim sourcedir As String
sourcedir = TextBox1.Text + "\"
Dim targetdir As String
targetdir = readValue + "\"
For Each filename In filelist
If System.IO.File.Exists(filename) Then
System.IO.File.Delete(filename)
End If
Next
Edit:
Thank you so very much. This is the code that I used, in case someone else has the same issue.
Dim sourcedir As String
sourcedir = TextBox1.Text + "\"
Dim targetdir As String
targetdir = readValue + "\"
Dim sourceFilePaths = My.Computer.FileSystem.GetFiles(sourcedir, FileIO.SearchOption.SearchAllSubDirectories)
Dim targetFilePaths = My.Computer.FileSystem.GetFiles(targetdir, FileIO.SearchOption.SearchAllSubDirectories)
'Compare only file names, ignoring paths, and get a list of duplicates.
Dim duplicateFileNames = sourceFilePaths.Select(Function(filePath) System.IO.Path.GetFileName(filePath)).
Intersect(targetFilePaths.Select(Function(filePath) System.IO.Path.GetFileName(filePath)))
'Combine target folder path with duplciate file names and delete each one.
For Each filePath In duplicateFileNames.Select(Function(fileName) System.IO.Path.Combine(targetdir, fileName))
System.IO.File.Delete(filePath)
Application.DoEvents()
Next
E.g.
Dim sourceFolderPath = "C:\SourceFolder"
Dim targetFolderPath = "C:\TargetFolder"
Dim sourceFilePaths = Directory.GetFiles(sourceFolderPath)
Dim targetFilePaths = Directory.GetFiles(targetFolderPath)
'Compare only file names, ignoring paths, and get a list of duplicates.
Dim duplicateFileNames = sourceFilePaths.Select(Function(filePath) Path.GetFileName(filePath)).
Intersect(targetFilePaths.Select(Function(filePath) Path.GetFileName(filePath)))
'Combine target folder path with duplciate file names and delete each one.
For Each filePath In duplicateFileNames.Select(Function(fileName) Path.Combine(targetFolderPath, fileName))
File.Delete(filePath)
Next
Here's an option that doesn't use LINQ:
Dim sourceFolderPath = "C:\SourceFolder"
Dim targetFolderPath = "C:\TargetFolder"
Dim sourceFilePaths = Directory.GetFiles(sourceFolderPath)
Dim targetFilePaths = Directory.GetFiles(targetFolderPath)
Dim sourceFileNames As New List(Of String)
For Each sourceFilePath In sourceFilePaths
sourceFileNames.Add(Path.GetFileName(sourceFilePath))
Next
For Each targetFilePath In targetFilePaths
Dim targetFileName = Path.GetFileName(targetFilePath)
If sourceFileNames.Contains(targetFileName) Then
File.Delete(targetFilePath)
End If
Next
It's important to note that both these examples are case-sensitive. Both the Intersect and Contains methods will accept an IEqualityComparer(Of String) though, so you can provide one to make them case-insensitive.

VB.net use string in Directory Path?

I apologise for my lack of basic VB.net knowledge but I'm looking to use the equivalent of %systemdrive% to find the drive containing Windows to check for an existing directory in VB.net - so I have the below.
Dim systemPath As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
If Not Directory.Exists("'systemPath'\MyFolder") Then
Directory.CreateDirectory("'systemPath'\MyFolder")
End If
Can someone help with using the systemPath string in the directory query? Thank you.
Well you should write
Dim systemPath As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
If Not Directory.Exists(Path.Combine(systemPath, "MyFolder")) Then
Directory.CreateDirectory(Path.Combine(systemPath, "MyFolder"))
End If
You could get the environment variable called %SYSTEMDRIVE% with Environment.GetEnvironmentVariable, but then the results obtained should be manually combined with current directory separator char ("\") because I have not found any way to convince Path.Combine to build a valid path with only the system drive (I.E. C: )
Dim sysDrive = Environment.GetEnvironmentVariable("SystemDrive")
Dim myPath = sysDrive & Path.DirectorySeparatorChar & "MyFolder"
IO.Path has methods that should be used IMHO
Dim sysDrive As String = Environment.GetEnvironmentVariable("SystemDrive") & IO.Path.DirectorySeparatorChar
Dim myPath As String = IO.Path.Combine(sysDrive, "FolderName")

How to get the file name of a file in VB?

I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box

Copy files in VB.NET

I'm trying to create an installer-like application. Here is what its supposed to do: create a directory in C: and name it batch. Then copy the files from the folder and move it to the C:\batch directory. But the copying of files doesn't work.
How am I supposed to put the exact directory in here if that exact directory does not apply to all? What do I do with it? If the file that is to be copied is from: E:\Documents and Settings\Rew\My Documents\Visual Studio 2008\Projects\batch\batch
I want it to be universal. So that wherever the file maybe it could always copy it regardless of where it is located.
Somehow the creating of a directory work.
Dim FileToCopy As String
Dim NewCopy As String
Try
Directory.CreateDirectory("C:\Batch")
FileToCopy = "\batch\batch\ipconfigrenew.bat"
FileToCopy = "\batch\batch\ipconfigrelease.bat"
FileToCopy = "\batch\batch\ipconfigflushdns.bat"
NewCopy = "C:\Batch"
If System.IO.File.Exists(FileToCopy) = True Then
System.IO.File.Copy(FileToCopy, NewCopy)
MsgBox("File Copied")
End If
Catch
End Try
MsgBox("Done")
First, the only value in FileToCopy by the time you do the copy is the last one. I'm having trouble parsing the question to figure out what you need, but I would first do this:
Dim FileToCopy(3) As String
FileToCopy(0) = "\batch\batch\ipconfigrenew.bat"
FileToCopy(1) = "\batch\batch\ipconfigrelease.bat"
FileToCopy(2) = "\batch\batch\ipconfigflushdns.bat"
Dim NewCopy As String = "C:\Batch"
Dim s As String
For Each s In FileToCopy
If System.IO.File.Exists(s) = True Then
System.IO.File.Copy(s, NewCopy)
MsgBox("File Copied")
End If
Next
Next, I would decide if I needed to write this in a more generic way.