Re: Exception: Cannot create a file when that file already exists.

  •  08-31-2010, 9:47 PM

    Re: Exception: Cannot create a file when that file already exists.

    Try this:
     

    Protected Sub Uploader1_FileUploaded(ByVal sender As Object, ByVal args As CuteWebUI.UploaderEventArgs) Handles Uploader1.FileUploaded

    Dim fileExt As String = System.IO.Path.GetExtension(args.FileName).ToUpper

    If (fileExt = ".GIF") Or (fileExt = ".JPG") Or (fileExt = ".JPEG") Then

    Dim saveDir As String = "pictures\"

    Dim appPath = Request.PhysicalApplicationPath

    Dim savePath As String = appPath + saveDir

    'Obtener el nombre del archivo.

    Dim fileName As String = args.FileName

    'Crear una ruta y nombre para checar si hay archivos duplicados

    Dim pathToCheck As String = savePath + fileName

    'Crear un nombre temporal para checar duplicados

    Dim tempfileName As String

    'Checar si existe un archivo con el mismo nombre que el que se va a subir

    If (System.IO.File.Exists(pathToCheck)) Then

    Dim counter As Integer = 1

    While (System.IO.File.Exists(pathToCheck))

    ' Si existe un archivo con el mismo nombre, le agrega un contador numerico al principio

    tempfileName = counter.ToString() + fileName

    pathToCheck = savePath + tempfileName

    counter = counter + 1

    End While

    fileName = tempfileName

    End If

    ' Agregar el nombre a la ruta fisica

    savePath += fileName

    'Guardar el archivo

    args.CopyTo(savePath)

    Dim InsertSql As String = "INSERT INTO pictures (picture) VALUES ?picture)"

    Dim cmd As New MySqlCommand(InsertSql, conn)

    Try

    conn.open()

    With cmd

    .CommandType = CommandType.Text

    .Parameters.AddWithValue("?picture", fileName)

    .Prepare()

    .ExecuteNonQuery()

    End With

    Catch ex As Exception

    Errores(ex.Message)

    Finally

    If Not conn Is Nothing Then
    conn.close()
    End If

    End Try

    End If

    End Sub

View Complete Thread