VB.Net files are not zipping correctly - vb.net

I have created a project in vb.net that saves a Solid Edge assembly in multiple formats and then zips those formats individually and deletes the unzipped files from the directory. Until very recently, the program was working fine. Now, however, the files are not zipped in the directory. All that happens is that a file with the extension .7z is created one level up (ie I want files to be zipped in C:\Folder\New Folder but the .7z file is created in C:\Folder). Here is some of the project code:
' The extensions are stored in the INI file and must be retrieved
Extension = GetIniValue("CADMakros", "FileFormatExtensions3D", "C:\Windows\RTSettings.INI")
' Checks if there are extensions in the INI file
If Extension = "" Or Extension = " " Then
MsgBox("Keine Erweiterungen in «RTSettings.ini» eingetragen")
Exit Sub
End If
' The extensions are separated by a ";" in the INI file
' Therefore, they are split up into separate strings and sorted in the NewExtensions array
'The NewExtensions array does not have a defined size so that an arbitrary number of extensions can be added to the INI file
NewExtensions = Extension.Split(";")
' The spaces are removed from the extension strings
For i = 0 To UBound(NewExtensions)
NewExtensions(i) = NewExtensions(i).Replace(" ", "")
Debug.Print(NewExtensions(i))
Next
' An array containing the filenames is created whose size is dependent on the number of extensions
' Therefore, the array size changes when the INI file is modified
Dim NewFileNames(NewExtensions.Count) As String
Dim zippedFileNames(NewFileNames.Length) As String
' Remove solid edge extension
FileName = Microsoft.VisualBasic.Left(FileName, InStrRev(FileName, ".") - 1)
' Uses the file name as a default response for the input box
FileName1 = InputBox("Dateinamen eingeben", DefaultResponse:=FileName)
If FileName1 = " " Then
MsgBox("Bitte Dateinamen eingeben")
Exit Sub
ElseIf FileName1 = "" Then
Exit Sub
End If
ProgressBar1.Value = 30
' Creates a new file name that acts as the path of the file
For k = 0 To (NewExtensions.Length - 1)
NewFileNames(k) = ChosenFile & "\" & FileName1 & NewExtensions(k)
Next
' The files are saved
For k = 0 To (NewFileNames.Count - 2)
objDocument.SaveAs(NewFileNames(k))
' The progress of the program is sent to the backgroundWorker so it can update the progress bar accordingly
BackgroundWorker1.ReportProgress(30 + (k / (NewFileNames.Count - 2)) * 65)
' The program must be given time to update the progress bar
System.Threading.Thread.Sleep(200)
Next
For j = 0 To NewFileNames.Length - 2
For i = 0 To UBound(NewExtensions)
If NewFileNames(j).Contains(NewExtensions(i)) Then
zippedFileNames(j) = NewFileNames(j).Substring(0, NewFileNames(j).Length - NewExtensions(i).Length)
zippedLocation(j) = zippedFileNames(j) + "-" + NewExtensions(i).Substring(1)
End If
Next
Next
' The files are zipped
Shell(zipPath & " a " & zippedLocation(0) & ".zip " & NewFileNames(0))
Shell(zipPath + " a " + zippedLocation(1) + ".zip " + NewFileNames(1))
Shell(zipPath + " a " + zippedLocation(2) + ".zip " + NewFileNames(2))
'Dim save As New ProcessStartInfo(zipPath)
'save.Arguments = zipPath & " a -tzip " & zippedLocation(0) & ".zip " & NewFileNames(0)
'Process.Start(save)
' The program is given time to zip the file before it is deleted (this ensures the zipped file contains the required information)
Thread.Sleep(2000)
''The unzipped file is deleted from the computer
My.Computer.FileSystem.DeleteFile(NewFileNames(0))
My.Computer.FileSystem.DeleteFile(NewFileNames(1))
My.Computer.FileSystem.DeleteFile(NewFileNames(2))
ProgressBar1.Value = 100
The zip command is near the bottom (they are shell commands). Sorry about the message box messages, they're in German because I'm doing this for a German company.
Thank you in advance!

Related

".gz" extraction problem via VBA Shell and 7z command line

I'm trying to create a function that returns unpacked file. It's only 1 file in archive. The problem comes with an unpacking part. I'm trying to get unpacked archive to the same folder as archive. Shell returns different not 0 values. The name seems not to be too long: Len( myFullPath ) = 101. The file name is - VZN_2022.csv.gz (packed file name)
I do not see a result of unpacking: there are no unpacked file in the folder. I use the code below:
Function Foo (ByVal myFullPath as String) as Boolean ' myFullPath = folder path + "\" + filename
Call unpackeFile( CreateObject("Scripting.FileSystemObject").GetFile(myFullPath) )
End Function
Function unpackeFile(ByRef archive As Object) As Object
....
commandStr = "C:\Program Files\7-Zip\7zFM.exe e " & archive.Path
Call Shell(commandStr, 0)
....
End function
Debug.Print commandStr
C:\Program Files\7-Zip\7zFM.exe e \\av-fs01.av.local\profiles$\meltek\Desktop\VZN_2022.csv.gz
You need to wrap the path to the executable in quotation marks too, because it has a space in it - otherwise Shell will read up to the first space (i.e., C:\Program)and assume the rest are arguments:
Function unpackeFile(ByRef archive As Object) As Object
....
commandStr = Chr(34) & "C:\Program Files\7-Zip\7zFM.exe" & Chr(34) & " e " & Chr(34) & archive.Path & Chr(34)
Call Shell(commandStr, 0)
....
End function

How do I create a zip folder of multiple files with the same filename, but that have different file extensions

I need to create zip folders containing multiple files that will have the same filename, but different file extension. For example, in one folder I will have:
Field 1.shp
Field 1.shx
Field 1.prj
Field 1.dbf
Field 2.shp
Field 2.shx
Field 2.prj
Field 2.dbf
etc..
I need to zip all Field 1 files together in Field 1.zip, Field 2 files together in Field 2.zip etc. looping through the folder.
Here I am currently:
Private Sub btnZipFiles_Click(sender As Object, e As EventArgs) Handles btnZipFiles.Click
Dim dir = SelectedPath.Text
Dim reqextensions As String = "*.dbf,*.prj,*.shp,*.shx"
Dim files = Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
For Each file In files
Using zip As New ZipFile
zip.AddFile(file, "")
zip.Save(file + ".zip")
End Using
Next
End Sub
I've added "dotnetzip" and Imported Ionic.zip. The above code will zip each .dbf, .prj, .shp, and .shx file individually, but I am stuck on how to combine each 4 files into one zip file.
Thank you in advance.
Here is what I came up with with my desired result looping through the files previously called via Directory.EnumerateFiles:
For Each file In files
Using zip As New ZipFile
zip.AddFile(dir + "\" + Path.GetFileNameWithoutExtension(file.Name) + ".dbf", "")
zip.AddFile(dir + "\" + Path.GetFileNameWithoutExtension(file.Name) + ".prj", "")
zip.AddFile(dir + "\" + Path.GetFileNameWithoutExtension(file.Name) + ".shx", "")
zip.AddFile(dir + "\" + Path.GetFileNameWithoutExtension(file.Name) + ".shp", "")
zip.Save(zippath + Path.GetFileNameWithoutExtension(file.Name) + ".zip")
End Using
Next
This takes each file part I require (.dbf, .prj, .shp, .shx) with a matching filename and zips each together in a filename.zip file.

Open a file in a new instance of program

All;
I have a bit of code I've written that opens a design blueprint when I scan a bar code. It works well enough, but I'd like to open a new instance of the design software (Solidworks) and have the print display in the new instance. Right now, no matter how many Solidworks instances I have open, the print will only open in the first instance started.
The line commented out below is the line that works, just not in the right instance. The line below that is what I'd expect to work, but it returns a 'file not found' even though the path to solidworks and the print path are both correct.
Any explanation as to why this isn't working would be much appreciated as I'm obviously very new at this...and have no idea what I'm doing.
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim barcode As String = tb_barcode.Text
Dim filename As String = tb_barcode.Text
'Add File Extension to end of path
Dim ext As String = ".SLDDRW"
'Split job number from detail number in barcode textbox
barcode = Split(tb_barcode.Text, ".")(0)
filename = Split(tb_barcode.Text, ".")(1)
'- This works, just in primary instance
'System.Diagnostics.Process.Start("G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext)
'- This does not work
System.Diagnostics.Process.Start("'C:\Program files\Solidworks Corp\Solidwork\SLDWORKS.exe' 'G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext + "'")
Catch
MessageBox.Show("File Not Found")
End Try
End Sub
Sorry for naive approach but shouldn't there be a comma in Process.Start between 2 arguments?
Start(String, String)
Starts a process resource by specifying the name of an application and a set of command-line arguments, and associates the resource with a new Process component. docs
Why don't you use the Application.ExecutablePath.That returns the Application's path with its full name. Then your code should be
System.Diagnostics.Process.Start(Application.Executablepath, "G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext + "'")
Also make sure that the second string argument is a valid path.

Uploading File To Website

I am still a beginner with VBA, so if you need further explanation or I am not describing my problem correctly please let me know.
I am trying to achieve the following:
Upload a file from my computer to a website (You can only try to upload if you login, so sadly I cannot share a link)
In order to achieve this I need to do three things:
1) Click the "Upload" Button
2) Insert the Filepath into the search field of the PopUp Window
3) Click the "Open" Button
The website looks like this:
The PopUp Window looks like this:
The HTML code of the upload field is the following:
<div class="button-wrapper">
<input class="design-file-input" type="file">
<a class=" button prio1" href="javascript:void(0);">Design hochladen</a>
</div>
I guess there might be two solutions two my problem, however, I am not able to realize my plans.
IDEA 1
Somehow get the filepath into the input field and the page to download it
Therefore I tried the vba following VBA codes:
objIE.document.getElementsByClassName("design-file-input")(0).Value
objIE.document.getElementsByClassName("design-file-input")(0).innerText
And then try to somehow make the website submit my entry.
IDEA 2
Click the "Design Hochladen" Button.
objIE.document.getElementsByClassName("button-wrapper")(0).Click
But then the PopUp window comes up and I don't know how to control it with VBA
I am happy to hear and try your suggestions!! If you need any further details, just let me know! Thank you so much if you can give me any advice
Directly assigning the file path to the value of that specific HTML element does not work. A while ago, I had the same issue (automatically passing a file to an upload file dialog). After a long googling session, I found following solution. Unfortunately, I could not find the link from where I took this answer. In case I come accross the website, I will share the link with you:
Dim FilePath As String
Dim FileName As String
FilePath = Environ$("temp") & "\"
FileName = "test_file_for_upload" & ".xlsx"
UploadFile DestURL, FilePath & FileName, "file" 'Usage
'******************* upload - begin
'Upload file using input type=file
Public Sub UploadFile(DestURL As String, FileName As String, _
Optional ByVal FieldName As String = "File")
Dim sFormData As String, d As String
'Boundary of fields.
'Be sure this string is Not In the source file
Const Boundary As String = "---------------------------0123456789012"
'Get source file As a string.
sFormData = GetFile(FileName)
'Build source form with file contents
d = "--" + Boundary + vbCrLf
d = d + "Content-Disposition: form-data; name=""" + FieldName + """;"
d = d + " filename=""" + FileName + """" + vbCrLf
d = d + "Content-Type: application/upload" + vbCrLf + vbCrLf
d = d + sFormData
d = d + vbCrLf + "--" + Boundary + "--" + vbCrLf
'Post the data To the destination URL
IEPostStringRequest DestURL, d, Boundary
End Sub
'sends URL encoded form data To the URL using IE
Sub IEPostStringRequest(URL As String, FormData As String, Boundary As String)
'Create InternetExplorer
Dim WebBrowser: Set WebBrowser = CreateObject("InternetExplorer.Application")
'You can uncoment Next line To see form results
WebBrowser.Visible = True
'Send the form data To URL As POST request
Dim bFormData() As Byte
ReDim bFormData(Len(FormData) - 1)
bFormData = StrConv(FormData, vbFromUnicode)
WebBrowser.navigate URL, , , bFormData, _
"Content-Type: multipart/form-data; boundary=" + Boundary + vbCrLf
Do While WebBrowser.Busy
' Sleep 100
DoEvents
Loop
'WebBrowser.Quit
End Sub
'read binary file As a string value
Function GetFile(FileName As String) As String
Dim FileContents() As Byte, FileNumber As Integer
ReDim FileContents(FileLen(FileName) - 1)
FileNumber = FreeFile
Open FileName For Binary As FileNumber
Get FileNumber, , FileContents
Close FileNumber
GetFile = StrConv(FileContents, vbUnicode)
End Function
'******************* upload - end
The third argument "file" denotes the ID of the HTML element which needs to be triggered.
Hope this solution workds for you as well

VB.Net - "My.Computer.FileSystem.CopyDirectory" Does Not Copy Directory or Permissions of Directories Inside Target Directory

I tried to be as descriptive in my title as possible, but to clarify I have a VB.Net application and I'm attempting to copy a directory to another machine with file permissions and all child files/folders.
Using "My.Computer.FileSystem.CopyDirectory", the directory that is chosen to be copied does NOT get copied over like the MSDN implies; but instead the contents of the directory are copied to the destination directory. If there is a folder inside of that directory, the folder is copied but the permissions of said folder are NOT. Both of these things pose a huge issue because it's imperative that the original folder's permissions, and any other folders inside of the original folder, get copied along with it. This is possible using PowerShell, is it possible using VB.Net?
Thanks in advance.
For Each item As String In stations
copyTo = stations([i].ToString)
If IsHostAvailable(copyTo) Then
LogBreak()
LogOutput(TimeStamp() + ": " + copyTo + " available. Beginning file push...")
copyTo = "\\"
copyTo = Path.Combine(copyTo, stations([i].ToString))
copyToLoc1 = copyTo.ToString
copyToLoc1 = Path.Combine(copyTo, pushLocationBox1.ToString.Remove(0, 36))
LogBreak()
LogOutput(TimeStamp() + ": " + "Coyping- " + "\n" + pushFrom1 + "\n" + "...to station '" + copyTo + "'.")
If (File.Exists(pushFrom1) AndAlso (System.IO.Directory.Exists(copyToLoc1))) Then
Dim pushFileName As String = Path.GetFileName(pushFrom1)
My.Computer.FileSystem.CopyFile(pushFrom1, Path.Combine(copyToLoc1, pushFileName), True)
LogOutput(TimeStamp() + ": " + "File 1 copied.")
ElseIf (File.Exists(pushFrom1) AndAlso (System.IO.Directory.Exists(copyToLoc1) = False)) Then
Directory.CreateDirectory(copyToLoc1)
LogOutput(TimeStamp() + ": " + "Directory created.")
My.Computer.FileSystem.CopyFile(pushFrom1, copyToLoc1, True)
LogOutput(TimeStamp() + ": " + "File 1 copied.")
ElseIf (Directory.Exists(pushFrom1)) Then
My.Computer.FileSystem.CopyDirectory(pushFrom1, copyToLoc1, True)
Dim srcPerms As New FileInfo(pushFrom1)
Dim destPerms As New FileInfo(Path.Combine(copyToLoc1, pushFrom1))
Dim permissions As FileSecurity = srcPerms.GetAccessControl()
permissions.SetAccessRuleProtection(True, True)
destPerms.SetAccessControl(permissions)
LogOutput(TimeStamp() + ": " + "Directory 1 copied.")
Else
LogOutput(TimeStamp() + ": " + "The file or directory selected to be copied can no longer be found. (#1)")
MsgBox("The file or directory selected to be copied can no longer be found. (#1)", MsgBoxStyle.Critical, "Error!")
End If
Else
LogOutput(TimeStamp() + ": " + "Ping request timed out on " + copyTo + ". Moving to next station...")
FailOutput(copyTo)
End If
i += 1
Next
i think the directory path in copyToLoc1 is not correct, i tested code below and it works.
My.Computer.FileSystem.CopyDirectory("E:\Users\test1\Desktop\test", "E:\Users\test1\Desktop\test2", True)
Your program might not be storing info to copyToLoc1 correctly to debug and see if its the case
comment out this code
'My.Computer.FileSystem.CopyDirectory(pushFrom1, copyToLoc1, True)
add the following code
MsgBox(copyToLoc1)
You would get a msg with the new directory you trying to create.
see if its the correct directory you are trying to create.