leo leone
leo leone

Reputation: 63

vb.net copying file to another directory

I want to copying file from selected directory path to another directory with same filename. i try this code,

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click

    Try
        Dim openfile As New OpenFileDialog
        openfile.Filter = "JPG|*.jpeg;*.jpg|PNG|*.png"
        If (openfile.ShowDialog = Windows.Forms.DialogResult.OK) Then
            TextBox3.Text = openfile.FileName
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

And then,

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click

    Try
        Dim source As String = TextBox3.Text
        FileCopy(dest, source)

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

error msg :

"System.UnauthorizedAccessException : Acces to D:\resource is denied"

Upvotes: 2

Views: 289

Answers (2)

Andrew Morton
Andrew Morton

Reputation: 25057

I am guessing that your variable dest refers to the destination directory. You need to combine it with the filename for the destination filename, not directory. Something like this...

Imports System.IO
'......
Dim destDir As String = "D:\resource"
Dim source As String = TextBox3.Text
Dim destFile As String = Path.Combine(destDir, Path.GetFileName(source))
FileCopy(source, destFile)

It would be better to use a variable to store the filename of the source rather than a control - if the TextBox is not set to be read-only then the user could accidentally change it.

Upvotes: 1

Chetan Sanghani
Chetan Sanghani

Reputation: 2111

An UnauthorizedAccessException occurs in below situation:

  • User does not have the required permission.
  • The file is in use.
  • File Path is a directory.
  • Path specified a read-only file.

Upvotes: 1

Related Questions