Exclude folder from being copied - vb.net

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

Related

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

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.

RENAME FILE TO ANOTHER FILES NAME PREFIX IN SAME DIRECTORY VISUAL BASIC

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

VB.NET - Problems trying to write a textfile

I have problems when trying to delete/create/write to this file.
The error:
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
The highlighted lines by debugger:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
(Any of two, if I delete one line, the other line takes the same error id)
The sub:
Public Sub C1Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not playerargs = Nothing Then
Dim Str As String
Dim Pattern As String = ControlChars.Quote
Dim ArgsArray() As String
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
objWriter.Close()
Next
End If
Next
If randomize.Checked = True Then
RandomiseFile(Temp_file)
End If
Process.Start(userSelectedPlayerFilePath, playerargs)
If autoclose.Checked = True Then
Me.Close()
End If
Else
MessageBox.Show("You must select at least one folder...", My.Settings.APPName)
End If
End Sub
First, File.Create creates or overwrite the file specified, so you don't need to Delete it before.
Second, initializing a StreamWriter as you do, blocks the file and therefore you can't recreate it after.
So, simply move the StreamWriter intialization after the File.Create, or better, remove altogether the File.Create and use the StreamWriter overload that overwrites the file
....
If Not playerargs = Nothing Then
....
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Using objWriter As New System.IO.StreamWriter(Temp_file, false)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
' objWriter.Close()
Next
End If
Next
End Using ' Flush, close and dispose the objWriter
....
Noticed also that you close the writer while still inside the loop, use the Using statement to close correctly the writer after the work is done.
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
That means the file is opened or been used by another process.
Open your task manager and check if the file is there, then close it or simplex end the process.
I have had the same issue but I got it solved by closing the file.
Hope this helps!
From your details it seems that you are willing to delete if file exists and creates a new one.
I would suggest to remove this line:
System.IO.File.Create(Temp_file)
and move this line just over the streamwriter line:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
Something like this would help you:
Partial code:
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
' Delete file if exists
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
' Create file for write.
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
...
...
...