Tuesday, December 23, 2008
How to Copy a file and its extension Using VB.NET
Hi, If you go beyond this line then I can assume you are somewhat a VB programmer.
I have left this snippet for you to add to your sub proceedure so you can use your vb code to copy any file to a certain location on your PC. But then again your creativity must drive you to know that the file name could be made a dynamic parameter gotten from the user.
I have tried the snippet out with my Visual Studio 2008 and it does what it is meant to do.
Enjoy the snippet and get back if it does not work for you with your error prompt.
.....................VB.NET CODE STARTS HERE.......................................................................
' On my form, i have an Open file dialog Object called "ofd" , a Button called "cmdcopy"
' and then voila i am set to go
Private Sub cmdcopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdcopy.Click
ofd.ShowDialog()
Dim filetocopy As String
Dim stlen As Integer
filetocopy = ofd.FileName
Dim ext As String
Trim(filetocopy)
Dim position As Integer
' We first try to get the index of the "." symbol in the string
position = InStr(filetocopy, ".")
stlen = filetocopy.Length
ext = filetocopy.Substring(position - 1, (stlen - position) + 1)
Dim newfile As String = "c:\newfile78" & ext ' At this point i choose to declare my new file
If File.Exists(newfile) = True Then
Dim overwrite As Integer
overwrite = MessageBox.Show("Do you want to overwrite the existing file", "Overwrite file?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If overwrite = vbYes Then
File.Delete(newfile)
File.Copy(filetocopy, newfile)
MessageBox.Show("Successfully Copied" & vbNewLine & filetocopy & "to" & newfile)
ElseIf overwrite = vbNo Then
Exit Sub ' I am asking my my sub to exit because user clicks No
End If
End If
' If it does not exist it should be copied
File.Copy(filetocopy, newfile & ext)
MessageBox.Show("Successfully Copied" & vbNewLine & filetocopy & "to" & newfile)
End Sub
........................................VB CODE ENDS HERE.................................................
Subscribe to:
Post Comments (Atom)


0 comments:
Post a Comment