How to overwrite a file in specific folder with a file in my program's resources - vb.net

I have a file named "something.a binary extension" "not a txt extension" in my program's resources and the same file exists in another folder and named "Something.a binary extension" too.
I want to copy my resources file and replace the existing file with it.
My program has 2 button controls, one for browsing to get the path from OpenFileDialog1 and the other to copy my resources file and replace the existing file "Which have the same name" by it, and 1 TextBox to display the path.
My program has a manifest file to run as Adminstrator with level="highestAvailable.
I use this code:
Public Class Form1
Dim Path_of_folder As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
'getting the path
OpenFileDialog1.ValidateNames = False
OpenFileDialog1.CheckFileExists = False
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.FileName = "somthing.exe"
OpenFileDialog1.ShowDialog()
TextBox1.Text = System.IO.Path.GetFullPath(OpenFileDialog1.FileName)
TextBox1.Text = TextBox1.Text.Replace("somthing.exe", "").Trim()
Path_of_folder = TextBox1.Text 'we got the path
End Sub
Private Sub BtnCopy_Click(sender As Object, e As EventArgs) Handles BtnCopy.Click
FileCopy(My.Resources.somthing, Path_of_folder) ' this got Error when i use it, but the program can Run
End Sub
End Class

Related

Limited Multiselect in open file dialog?

I want the user to have the option to select multiple files through openfiledialog which I have in my code, but then if the user selects a file from one folder he is then restricted to select another file only from this specific folder. What is the best way to approach to this problem?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim openfiledialog1 As New OpenFileDialog
With openfiledialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
End With
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
For Each mfile As String In openfiledialog1.FileNames
'' Add all filenames in a txt file, in a column
Next
End If
End Sub
As far as I know, OpenFileDialog doesn't offer a way to prevent the user from navigating to another directory.
One approach would be to create a class-level variable that holds the value of the recently used directory path. Then, whenever a new file is selected, you check its directory path against the one previously stored. If it matches, continue. If not, break the operation and report to the user.
Here's a complete example:
Private openFileDialog1 As New OpenFileDialog
Private modelsDirectory As String = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With openFileDialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
.FileName = Nothing
' Open the dialog and navigate to the previous direcoty by default.
.InitialDirectory = modelsDirectory
End With
If openFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub
Dim dirPath As String = IO.Path.GetDirectoryName(openFileDialog1.FileName)
If modelsDirectory IsNot Nothing AndAlso
Not dirPath.Equals(modelsDirectory, StringComparison.OrdinalIgnoreCase) Then
MessageBox.Show("Models must be selected from the following directory:" &
vbNewLine & modelsDirectory, "Restricted Directory")
Exit Sub
End If
' Store the value of the current directory path.
modelsDirectory = dirPath
For Each filePath As String In openFileDialog1.FileNames
' TODO: use the selected files as you see fit.
Next
End Sub
You might want to remove this restriction at some point (e.g., if you clear the list of selected files). You can achieve that by simply setting modelsDirectory to Nothing:
Private Sub ClearFilesList
' TODO: clear the files.
modelsDirectory = Nothing
End Sub

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

How To Save/Recall Folderbrowserdialog SelectedPath

I'm currently teaching myself (with the help of SO & Google) VB.Net to create a launcher for a multiplayer mod and I need users upon first launch of my application to input where their folder is stored, so far I have;
Dim folderDlg As System.Windows.Forms.FolderBrowserDialog
folderDlg = New System.Windows.Forms.FolderBrowserDialog
folderDlg.Description = "Please select your multiplayer folder"
If My.Settings.isFirstRun Then
My.Settings.isFirstRun = False
My.Settings.Save()
folderDlg.ShowDialog()
Else
End If
The button to run the mod itself
Private Sub Launch_mp_Click(sender As Object, e As EventArgs) Handles Launch_mp.Click
If My.Computer.FileSystem.FileExists("launcher.exe") Then
Process.Start("launcher.exe")
Timer2.Interval = 1000
Timer2.Start()
End If
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
p = Process.GetProcessesByName("eurotrucks2")
If p.Count > 0 Then
Timer2.Stop()
Me.WindowState = FormWindowState.Minimized
Me.Visible = True
Else
End If
End Sub
I'm confused as to how I can store the users selected path and then recall it later on for the button without always asking for the dir.
You are almost there:
You have various options where to store the information: registry, old-style using ini-files or in the config file of your application. I would suggest using the config file since you already store the isFirstRun-varialbe in the config. In project explrorer look at the "My Project" folder and double click an item called "Settings". Add a setting of type string called "ModFolder". After that you will be able to access the value of that setting using My.Settings.ModFolder varialbe (see here).
Use the FolderBrowserDialog to store the folder (see here)
if folderDlg.ShowDialog() = DialogResult.Ok then
My.Settings.ModFoler = folderDlg.SelectedPath
My.Settings.Save
end if
When your application starts next time the ModFolder-variable will automaticall hold the value stored so instead of If My.Settings.isFirstRun Then I would check:
If File.Exists(Path.Combine(My.Settings.ModFolder, "AppToStart.Exe")) then
...
end if
If the file exists launch it, if not re-show the dialog to pick the folder.

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.NET - How to Drag a File From Outlook 2010 to My Form?

I'm developing an application to read XML files, get its data and populate some field. SO, I've implemented two ways to get the file: through a command button and through the drag and drop form event. Everything is OK if I use a file stored in a folder in my computer. I can drag the file, the cursor changes its appearance to the copy effect etc. However, when I try doing it dragging a file as an attachment of Outlook (my version is the 2010), I see that the cursor assumes the forbidden effect and the file is not read.
Please, see below the implementation I did, which is working only for files stored in a folder in my computer. I would like to know what more I have to implement to allow drag a file from Outlook.
Thank you in advance.
Private Sub FrmJIG_DragDrop(sender As Object, e As DragEventArgs) _
Handles Me.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
Dim filestype() As String
filestype = e.Data.GetData(DataFormats.FileDrop)
Dim sReader As New StreamReader(filestype(0))
'get the filename from the file without the path
Dim file_name As String = Path.GetFileName(filestype(0))
'check the extension of the file
If Path.GetExtension(filestype(0)).ToLower() = ".xml" Then
'Read the xml file
For Each path In files
ReadXMLFile(path)
Next
Else
'warning about the file type
MessageBox.Show("Only XML files are supported!", "Warning!", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
End If
End Sub
Private Sub FrmJIG_DragEnter(sender As Object, e As DragEventArgs) _
Handles Me.DragEnter
'change the cursor type to drag and drop type
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
Please try with
Private Sub FrmJIG_DragEnter(sender As Object, e As DragEventArgs) _
Handles Me.DragEnter
'change the cursor type to drag and drop type
If e.Data.GetDataPresent(DataFormats.FileDrop) or e.Data.GetDataPresent("FileGroupDescriptor") Then
e.Effect = DragDropEffects.Copy
End If
End Sub