Save file in a new folder? - vb.net

I'm looking to make a program that will open a file and upon saving it, the program will save it into a new folder, leaving the original file unchanged.
However, none of the codes I've tried using have worked.
How do I make a new folder that will go into the FilePath of the loaded file?
How do I then save into that folder?
I tried this and got the error.. "False was not found or could not be accessed"
Private Sub SaveChangesToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveChangesToolStripMenuItem1.Click
newFilePath = FilePath + "\" + newFolderName + "Folder"
Try
Dim Writer As New PackageIO.Writer(newFilePath = orgFilePath + "\" + newFolderName, "Folder 1", PackageIO.Endian.Big)
System.IO.Directory.CreateDirectory(newFilePath)
I tried this code here and it seemed to be the closest to working, but said the file path wasn't valid; I'm assuming because it's including the file they selected, not just the folders involved.
Private Sub SaveChangesToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveChangesToolStripMenuItem1.Click
newFilePath = FilePath + "\" + newFolderName + "Folder"
Try
Dim Writer As New PackageIO.Writer(newFilePath, PackageIO.Endian.Big)
System.IO.Directory.CreateDirectory(newFilePath)

Try something along these lines:
Dim orgFilePath as String
Dim newFolderName as String
Dim newFilePath as String
'you will need to set the path of the original file and give a name for the new folder
newFilePath = orgFilePath + "\" + newFolderName
'creates new directory (folder)
System.IO.Directory.CreateDirectory(newFilePath)
'then put the code to save your file to the newFilePath variable
Hope that helps

Related

How to fix copied folder name

I have a vb application which copies folders and its subfolder that is working properly. My problem is that it is not copying the correct folder name of the folder being copied.
Like if I copy the folder with this location: C:\Users\Documents\Sample_Folder
The output copied folder name would be "Documents".
C:\Users\Documents\Sample_Folder\Sample_Folder_2
The output copied folder name would be "Sample_Folder".
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
Dim SourcePath As String = txtBrowse.Text
Dim DestinationPath As String = "C:\Users\1000258123\Desktop\NEW"
Dim newDirectory As String =
System.IO.Path.Combine(DestinationPath,
Path.GetFileName(Path.GetDirectoryName(SourcePath)))
If Not (Directory.Exists(newDirectory)) Then
Directory.CreateDirectory(newDirectory)
End If
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(SourcePath, newDirectory)
MsgBox("Copy Successful")
End Sub

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?

Copying files back to a Specific Folder

This program extracts files from a folder that has been modified today, and after the files are placed into another folder a batch file then deletes the rest of the non-modified files in that source folder.
The last thing my program is supposed to do is copy files from separate folder, and place them back into that source folder.
But my program only extracts the modified files, deletes the rest of the files in that folder, but when I run the program to also copy and place the new files into the source folder it just doesn't do it. Does anyone know why?
Imports System.IO
Public Class frmExtractionator
' Dim txtFiles1 As Control
Dim sourceDirectory As String = "F:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "F:\FilesExtracted"
Dim originalDirectory As String = "F:\OriginalTestFiles"
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
If (IO.File.GetLastWriteTime(currentFileLoc).ToString("MM/dd/yyyy") = DateTime.Now.ToString("MM/dd/yyyy")) Then
MessageBox.Show(currentFileLoc & " moved", "Moved Succesfully")
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
End If
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
System.Diagnostics.Process.Start("F:\poop.bat")
Try
Dim txtFiles2 = Directory.EnumerateFiles(originalDirectory)
For Each currentFileLoc2 As String In txtFiles2
Dim fileName = currentFileLoc2.Substring(originalDirectory.Length + 1)
File.Move(currentFileLoc2, Path.Combine(sourceDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class
Change
Dim fileName = currentFileLoc2.Substring(originalDirectory.Length + 1)
to
Dim FileName = IO.Path.GetFileName(currentFileLoc2)

VB.net Selecting files and folders in a folder

I'm trying to select the files and folders inside a folder to zip up, but what it seems to be doing is selecting all the folders up to the folder i've selected and the files in the final folder but not the folders in there and zipping them up. So for example in tbFolder I have the string: "C:\Users\tomb\Desktop\DeOld\Mota7" I want to select this folder and zip up the entire contents of this folder, images and all. But whats happening is the following:
Its creating the folder structure up to the folder i want zipped and adding just the files in side this and not the folders. I'm guessing I need to tweak the line:
System.IO.Directory.GetFiles(DirectoryToZip)
Here is the entire code:
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
Dim ZipFile As String = "C:\Releases\" & drpService.Text & "-" & DateTime.Now.ToString("YYmmDD") & ".zip"
Dim DirectoryToZip As String = tbFolder.Text
Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
Using zip As ZipFile = New ZipFile
zip.AddFiles(filenames)
zip.Save(ZipFile)
End Using
End Sub
If you are using DotNetZip, there is an example on their site to add an entire directory
zip.AddDirectory(DirectoryToZip, "RootFolderInZip");

Rename directory using save filedialog filename

I Have a folder in this path
C:\Users\XXX\Desktop\Original\XXX\bin\Debug\Backup
And when I save my project with "XXX" name the same time I need to change the Backup Folder using that save filedialog name and it shouldn't overwrite it.
Can anyone suggest me how to do this:
Here is the code how I am doing it and it didn't work for me:
Private Sub SaveProject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveProject.Click
Using sfdlg As New Windows.Forms.SaveFileDialog
sfdlg.OverwritePrompt = True
sfdlg.InitialDirectory = "C:\"
sfdlg.FileName = "Untitled"
sfdlg.DefaultExt = "amk"
sfdlg.Filter = "AquaMark Project|*.amk"
If sfdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
With SaveData
frmDisplay.GCanvas1.UnselectCurrentAnotate()
.gAnnotates = frmDisplay.GCanvas1.gAnnotates
.Image = frmDisplay.GCanvas1.Image
End With
Using objStreamWriter As New StreamWriter(sfdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
x.Serialize(objStreamWriter, SaveData)
objStreamWriter.Close()
End Using
End If
sfdlg.Dispose()
System.IO.Path.GetFileNameWithoutExtension(sfdlg.FileName)
IO.Directory.Move(Application.StartupPath + "\Backup\", Application.StartupPath + "\Backup\" & System.IO.Path.GetFileNameWithoutExtension(sfdlg.FileName))
End Using
End Sub
But can anyone clearly mention me how to do it?
Based on the error, you most likely won't be able to save the file and change the backup folder name through the same SaveFileDialog.
Break it into two steps:
Save the file through the SaveFileDialog. Be sure to capture the filename from SaveFileDialog so you can use it in step 2, as it may be out of scope after you close the SaveFileDialog window.
Rename the backup folder using the command above, but after you've closed the SaveFileDialog so the handle is released.
EDIT
As I noted in step 1, you need to save the filename somewhere so you can use it in step 2.
Private Sub SaveProject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveProject.Click
' Set up a variable to hold the filenam
Dim fileName As String
Using sfdlg As New Windows.Forms.SaveFileDialog
sfdlg.OverwritePrompt = True
sfdlg.InitialDirectory = "C:\"
sfdlg.FileName = "Untitled"
sfdlg.DefaultExt = "amk"
sfdlg.Filter = "AquaMark Project|*.amk"
If sfdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
' Store the filename from the SaveFileDialog
fileName = sfdlg.FileName
With SaveData
frmDisplay.GCanvas1.UnselectCurrentAnotate()
.gAnnotates = frmDisplay.GCanvas1.gAnnotates
.Image = frmDisplay.GCanvas1.Image
End With
Using objStreamWriter As New StreamWriter(sfdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
x.Serialize(objStreamWriter, SaveData)
objStreamWriter.Close()
End Using
End If
'Calling Dispose is redundant since sfdlg was in a Using block
'sfdlg.Dispose()
' You can't use sfdlg.FileName here as the object is out of scope
'System.IO.Path.GetFileNameWithoutExtension(sfdlg.FileName)
'IO.Directory.Move(Application.StartupPath + "\Backup\", Application.StartupPath + "\Backup\" & System.IO.Path.GetFileNameWithoutExtension(sfdlg.FileName))
' Use the value in fileName from above
System.IO.Directory.Move(Application.StartupPath + "\Backup\", Application.StartupPath + "\Backup\" & System.IO.Path.GetFileNameWithoutExtension(fileName))
End Using
End Sub