Copy files in VB.NET - 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.

Related

Iterate through a directory to get subfolders and certain files

I am working on a program that will move files to a database, text files to be exact. The user will have a starting directory and inside will multiple sub folders and files and so on. I want to go through each Folder and sub folder looking for the text files and add them accordingly to the database so it resembles a directory structure in a way. In the program the files are organized such as the folders are "Categories" that are displayed into a tree view.I am only adding the folder names(as Categories) that do contain text files and their subs and so forth. As well I need to figure out where to plug in the adding of the "Category". As of right now I am using a couple of listboxes for my output until I can get it all figured out.
lstfiles.Items.Add(Dir)
For Each file In System.IO.Directory.GetFiles(Dir)
Dim fi As System.IO.FileInfo = New IO.FileInfo(file)
If fi.Extension = ".txt" Then
If lstRootFolderFiles.Items.Contains(file) = False Then
lstfiles.Items.Add(file)
AddFile(file, Gennumber(9999))
End If
End If
Next
For Each folder In System.IO.Directory.GetDirectories(Dir)
lstfiles.Items.Add(folder)
For Each file In System.IO.Directory.GetFiles(folder)
Dim fi As System.IO.FileInfo = New IO.FileInfo(file)
If fi.Extension = ".txt" Then
If lstRootFolderFiles.Items.Contains(file) = False Then
lstfiles.Items.Add(file)
End If
End If
Next
Next
I have gotten so far as to iterate through the directory and get files but it returns folders that are empty. And I need to figure out where I need to put in my addcategory function. And also remember the last one that was added so they can be added as a subcategory.
I think I am making a big mess of it all, or over thinking the whole thing.
Any assistance or guidance would be appreciated.Thank you
The end result that I came up with was much different from my original posting, as it was my way of thinking of how it was going to work. I split up the two main functions. Retrieving the Folders and retrieving the files.
DirEx is the Import Directory, CatID is the Tag of the selected Treenode where the folders are going to added in.
Private Sub DirImport_GetSubDirectories(ByVal DirEx As String, ByVal CatID As Integer)
Try
Dim ClsData As New clsNoteData
'Set the DatabaseFile Property of the class
ClsData.Database = LoadedLibraryDatabase
' Get all subdirectories
Dim subdirectoryEntries() As String = Directory.GetDirectories(DirEx)
' Loop through them to see if they have any other subdirectories
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
'If the Directory is not Empty
If Not Directory.GetFileSystemEntries(subdirectory).Length = 0 Then
Dim di As DirectoryInfo = New DirectoryInfo(subdirectory)
'Creating Random Number
Dim NewCatID As Integer = GenNumber(9999)
'Call for a new Sub Category
ClsData.NewSubCategoryNode(LoadedLibraryDatabase, NewCatID, CatID, di.Name, -1)
'Get files in the current Directory
DirImport_GetFiles(subdirectory, NewCatID)
'Get the next set of Subfolders
DirImport_GetSubDirectories(subdirectory, NewCatID)
End If
Next
Catch ex As Exception
End Try
End Sub
Private Sub DirImport_GetFiles(ByVal DirEx As String, ByVal CatID As Integer)
Dim Files() As String = Directory.GetFiles(DirEx, "*.txt")
Dim file As String
For Each file In Files
Dim clsNoteData As New clsNoteData
Dim fi As FileInfo = New FileInfo(file)
clsNoteData.Database = LoadedLibraryDatabase
clsNoteData.NewNote_ID = GenNumber(99999)
clsNoteData.NewNote_CatID = CatID
clsNoteData.NewNote_Title = Path.GetFileNameWithoutExtension(file)
clsNoteData.NewNote(False, file)
Next
End sub
So here it is for anyone who may want to do something similar.

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

VB NET - CopyDirectory only copies files? Why?

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?

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.

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