RENAME FILE TO ANOTHER FILES NAME PREFIX IN SAME DIRECTORY VISUAL BASIC - vb.net

Currently I have a code that will erase everything in a directory and place two template files in the said directory, a .dwg and a .jpg file. with button4.click
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.ClickDim path As
String = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer)& "C:\epds\WIP\"
System.IO.Directory.Delete(path, True)
My.Computer.FileSystem.CopyFile( _
"C:\Users\edevault\Documents\temp\temp.dwg", _
"C:\epds\WIP\temp.dwg", overwrite:=True)
My.Computer.FileSystem.CopyFile( _
"C:\Users\edevault\Documents\temp\BX-.jpg", _
"C:\epds\WIP\BX-.jpg", overwrite:=True)
Then I download a .zip file to the C:\epds\WIP\ directory and extract it manually.
What I would like to do is reverse the sequence and download the .zip then erase all in directory except the .zip and place the .dwg and .jpg file in the directory, and also rename the .dwg and .jpg files to the last 6 digits of the .zip file name.
Example:
SO123456.zip downloads to C:\epds\WIP\
button4.click erases all files except SO123456.zip and copies BX-.jpg and temp.dwg into C:\epds\WIP\ from C:\Users\edevault\Documents\temp\ then renames BX-.jpg to BX-123456.jpg and temp.dwg to 123456.dwg
The SO prefix of the SO123456.zip is not needed

may this help you
System.IO.File.Copy( "SO123456.zip", "temp\SO123456.zip" )
' same for other files you dont need to remove it
Dim strDirectory As String = " C:\epds\WIP\"
For Each foundFile As String In My.Computer.FileSystem.GetFiles(strDirectory, "*.*")
My.Computer.FileSystem.DeleteFile(foundFile, FileIO.UIOption.AllDialogs, FileIO.RecycleOption.DeletePermanently)
Next
System.IO.File.Copy( "SO123456.zip", "C:\epds\WIP\SO123456.zip" )
' same for other files you dont need to remove it

Here's how I was able to make this work:
Dim tmpDir As New IO.DirectoryInfo("C:\epds\WIP\")
Dim subd As IO.DirectoryInfo
Dim old, newf, old2, newf2, old3, newf3 As String
Dim withparts As String
Dim withoutparts As String
Dim zippath, extractpath, zip As String
Dim file As IO.FileInfo
'Button to extract ZIP, delete the ZIP, copy in DWG, BOX label, and CMD templates, and rename them the SO number
Public Sub CopyDWG_Click(sender As Object, e As EventArgs) Handles CopyDWG.Click
zippath = "C:\epds\WIP\"
extractpath = "C:\epds\WIP\"
Directory.GetFiles("C:\epds\WIP\")
For Each Me.file In tmpDir.GetFiles()
Next
Try
ZipFile.ExtractToDirectory(file.FullName, extractpath)
Catch ex As NullReferenceException
MsgBox("ZIP Archive not found.", MsgBoxStyle.Exclamation, "Design Dock")
Exit Sub
Catch ex As FileNotFoundException
MsgBox("ZIP Archive not found.", MsgBoxStyle.Exclamation, "Design Dock")
Exit Sub
Catch ex As InvalidDataException
MsgBox("ZIP Archive not found.", MsgBoxStyle.Exclamation, "Design Dock")
Exit Sub
End Try
My.Computer.FileSystem.DeleteFile(file.FullName)
For Each Me.subd In tmpDir.GetDirectories()
withparts = subd.Name
withoutparts = Replace(withparts, "SO", "")
Next
MsgBox("Archive unzipped to: " & subd.FullName, MsgBoxStyle.Information, "Design Dock")
Dim msg, title, response As String
Dim style As Single
msg = "Do you want to copy starter files to " & subd.FullName & "?"
title = "Design Dock"
style = MsgBoxStyle.YesNo Or MsgBoxStyle.Question
response = MsgBox(msg, style, title)
If response = MsgBoxResult.Yes Then
My.Computer.FileSystem.CopyFile("C:\TEMP\STARTER.DWG", subd.FullName & "\STARTER.DWG")
old = subd.FullName & "\STARTER.DWG"
newf = withoutparts & ".dwg"
Try
My.Computer.FileSystem.RenameFile(old, newf)
Catch ex As IOException
MsgBox("DWG already exists, nothing copied.", MsgBoxStyle.Information, "Design Dock")
My.Computer.FileSystem.DeleteFile(subd.FullName & "\STARTER.DWG")
End Try
My.Computer.FileSystem.CopyFile("C:\TEMP\BX-.JPG", subd.FullName & "\BX-.JPG")
old2 = subd.FullName & "\BX-.JPG"
newf2 = "BX-" & withoutparts & ".JPG"
Try
My.Computer.FileSystem.RenameFile(old2, newf2)
Catch ex As IOException
MsgBox("Box Label already exists, nothing copied.", MsgBoxStyle.Information, "Design Dock")
My.Computer.FileSystem.DeleteFile(subd.FullName & "\BX-.JPG")
End Try
My.Computer.FileSystem.CopyFile("C:\TEMP\BLANK.CMD", subd.FullName & "\BLANK.CMD")
old3 = subd.FullName & "\BLANK.CMD"
newf3 = withoutparts & ".CMD"
Try
My.Computer.FileSystem.RenameFile(old3, newf3)
Catch ex As IOException
MsgBox("Cut File already exists, nothing copied.", MsgBoxStyle.Information, "Design Dock")
My.Computer.FileSystem.DeleteFile(subd.FullName & "\BLANK.CMD")
End Try
Else
Exit Sub
End If

Related

Exclude folder from being copied

Hi I know how to copy files from one folder to the next, but I've run into a snag when we need to exclude a folder. More specifically the ".svn" folder. I've tried using Not SourceDir.Name = skipDir but that doesn't seem to make a difference.
This is my code. Thank you for the help.
Private Sub CopyDirectoryContents(sourcePath As String, destinationPath As String)
Dim SourceDir As DirectoryInfo = New DirectoryInfo(sourcePath)
Dim DestDir As DirectoryInfo = New DirectoryInfo(destinationPath)
Dim skipDir As String = ".svn"
Cursor = Cursors.WaitCursor
Try
If Not Directory.Exists(sourcePath) Then
MsgBox("The directory path entered does not exist. Please re-enter your source directory path", MsgBoxStyle.Exclamation, Title:="Missing source directory")
Return
txtSubfolder.Focus()
End If
If Not Directory.Exists(destinationPath) Then
MsgBox("The destination directory does not exist. Creating folder for it.", MsgBoxStyle.Exclamation, Title:="Missing folder")
Directory.CreateDirectory(destinationPath)
End If
Dim totalFiles As Integer = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories).Count
Dim fileCount As Integer = 1
For Each filePathString As String In Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)
Dim fileInfoItem As New FileInfo(filePathString)
Dim newFilePath As String = Path.Combine(destinationPath, fileInfoItem.Name)
If SourceDir.Exists And Not SourceDir.Name = skipDir Then
If File.Exists(newFilePath) Then
Dim result As Integer = MsgBox("File already exists in destination folder. Do you want to overwrite it?", MsgBoxStyle.YesNo, Title:="File already in folder")
If result = DialogResult.No Then
Continue For
ElseIf result = DialogResult.Yes Then
statusText = "Replacing found image"
BackgroundWorker1.ReportProgress(count, statusText)
File.Copy(filePathString, newFilePath, True)
End If
Else
File.Copy(filePathString, newFilePath)
End If
End If
fileCount = +1
Next
Catch ex As Exception
MsgBox("An error has occured. Please contact the system administrator. Exception: " & ex.Message)
End Try
End Sub

change extension and move file, using vb.net

I have the following code, which changes the extension of a txt to doc, and then moves it (from d:\1 to d:\2). The extension changes successfully, but it does not move, and I get an error
Cannot create a file when that file already exists.
Please suggest.
For Each filePath In Directory.GetFiles("D:\1", "*.txt")
File.Move(filePath, Path.ChangeExtension(filePath, ".doc"))
Next
Dim filesToMove = From f In New DirectoryInfo("d:\1").EnumerateFiles("*.doc")
For Each f In filesToMove
f.MoveTo("d:\2")
Next
This will check for an existing file of the same name and delete it first (you may want to handle this differently). It will then move and rename in one call to File.Move
Dim directory1 = "D:\1"
Dim directory2 = "D:\2"
For Each oldFileName In Directory.GetFiles(directory1, "*.txt")
Dim newFileName = Path.ChangeExtension(oldFileName, ".doc").Replace(directory1, directory2)
If File.Exists(newFileName) Then File.Delete(newFileName)
File.Move(oldFileName, newFileName)
Next
ok, finally found the solution. not very professional, but works anyways: ( Many thanks to all members who have helped earlier)
Private Sub logchange(ByVal source As Object,
ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
Dim sourceDirectory As String = "D:\1"
Dim archiveDirectory As String = "D:\2"
Try
Dim jpgFiles = Directory.EnumerateFiles(sourceDirectory, "*.wav")
For Each currentFile As String In jpgFiles
Dim fileName = Path.GetFileName(currentFile)
Directory.Move(currentFile, Path.Combine(archiveDirectory,
Path.GetFileNameWithoutExtension(fileName) & ".doc"))
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
Dim sourceDirectory As String = "D:\1"
Dim archiveDirectory As String = "D:\2"
Try
Dim jpgFiles = Directory.EnumerateFiles(sourceDirectory, "*.wav")
For Each currentFile As String In jpgFiles
Dim fileName = Path.GetFileName(currentFile)
Directory.Move(currentFile, Path.Combine(archiveDirectory,
Path.GetFileNameWithoutExtension(fileName) & ".doc"))
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End If
End Sub

Visual basic : Generic GDI+ error when saving file

When I executed my program I created in visual basic. I got a GDI+ error when I tried to save an image from a picturebox.
If I run it on the PC, where I created the program(windows 10), I don't have any problems. When I run it on 2 different windows 7 PC's, I got the error.
The mapped networkdrive is the same ( Z:\ ) and writeable.
Here is the code:
Private Sub SaveImage(ByVal pathToSaveTo As String)
Try
Using bmp As New Bitmap(Picimage.Image)
bmp.Save(pathToSaveTo, Drawing.Imaging.ImageFormat.Jpeg)
End Using
Catch ex As Exception
MessageBox.Show("An error occurred:" & vbCrLf & vbCrLf & _
ex.Message, "Error Saving Image File", _
MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Try
End Sub
The button to start the action
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim dt As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim testOutput As String
testOutput = "Z:\" & naam & " " & Now.ToString("HH/mm/ss") & ".jpg"
SaveImage(testOutput)
nr.Focus()
End Sub
GDI is complaining about the filename you're using.
Here's the problem: testOutput = "Z:\" & naam & " " & Now.ToString("HH/mm/ss") & ".jpg"
You're generating a filename with slashes in the path. If those are meant to be directory names (a directory for each hour, minute and second respectively) then those directories need to ex that won't work as GDI will not create missing directories along a path for you. If the slashes are meant to be in the filename itself then it also won't work as slashes are not a valid filename character.
Change the slashes to underscores or hyphens or other characters allowed in filenames:
testOutput = "Z:\" & naam & " " & Now.ToString("HH_mm_ss") & ".jpg"

FTP Client uploads only 0KB files

I am having a small problem with my FTP client.
Choosing a file works, renaming that file with 4 variables works.
It's the upload that is causing me trouble.
Whenever a file is uploaded to the FTP server it says it is 0KB.
I am thinking of 2 possible problems:
Visual studio tells me that the variable file is used before it has been assigned a value, to make sure it isn't null i did the following.
Dim file As Byte()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
This Takes care of any possible Errors.
The second one is fName, same warning as with file, and I took care of it the same way.
another possibility is that my code just takes the 4 variables and makes that into a file and uploads it, hence the 0KB size....
Here's my code:
Dim Filename As String
Dim originalFile As String
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is ComboBox AndAlso DirectCast(Control, ComboBox).SelectedIndex > -1) Then
fName += CStr(Control.SelectedItem.Key) + "_"
End If
Next
Try
fName = path + fName.Substring(0, fName.Length - 1) + ".jpg"
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
MsgBox(enumerateCheckboxes(Filename))
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ip" & enumerateCheckboxes(Filename)), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("username", "password")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
If (Not Filename Is Nothing) Then
System.IO.File.ReadAllBytes(Filename)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
If (Not Filename Is Nothing) Then
FileSystem.Rename(originalFile, Filename)
End If
Dim strz As System.IO.Stream = request.GetRequestStream()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
End Sub
End Class
I have looked at multiple threads with the same problem as me.
Threads like this
But i dont believe this applies to my problem.
If you would be so kind to explain what i did wrong and how i can fix and avoid this in the future, my debugging is still a bit rough...
Thank you in advance!
Visual Studio is giving you that warning because you never assign anything to the file array. I think that on the line where you have:
System.IO.File.ReadAllBytes(Filename)
You really meant to have:
file = System.IO.File.ReadAllBytes(Filename)

Null Reference Exception when trying to upload a file via FTP

I made a FTP upload application, which changes the name of the file chosen in FileDialog to a set of variables from 4 ComboBoxes. But whenever i try to upload the file it says:
Path Cannot be Null Paramenter name: path
in the immediate window it says:
A first chance exception of type 'System.ArgumentNullException' occurred in mscorlib.dll
A first chance exception of type 'System.NullReferenceException' occurred in Microsoft.VisualBasic.dll
and this:
i've gone over the code multiple times but i do not understand what is wrong, since i am quite new to VB.
this is the code i used:
Dim Filename As String
Dim originalFile As String
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is ComboBox AndAlso DirectCast(Control, ComboBox).SelectedIndex > -1) Then
fName += CStr(Control.SelectedItem.Key) + "_"
End If
Next
Try
fName = path + fName.Substring(0, fName.Length - 1) + ".pdf"
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
MsgBox(enumerateCheckboxes(Filename))
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ip"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("username", "password")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
System.IO.File.ReadAllBytes(Filename)
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
FileSystem.Rename(originalFile, Filename)
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End Sub
Thank you in advance
An ArgumentNullException is not a NullReferenceException. It's telling you the argument to one of the functions is Nothing.
It's being caused in part by these two lines:
Filename = OpenDialog()
System.IO.File.ReadAllBytes(Filename)
In this case, it appears that your Filename is Nothing, because OpenDialog doesn't return a value. You'll need to return the file selected from the OpenFileDialog.