• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 232
  • Last Modified:

How to delete file that I uploaded to server by clicking Delete link on my DataGrid?

On a seperate page I uploaded a file and wrote the file_id, file_name, file_size, file_path and upload_date to my database.  
On the page posted below, I pull that information into a DataGrid.  I have a button column called Delete.  When Delete is clicked it deletes that data row.
How do I make it delete the file that is referenced in the DataGrid in the file_path column?


Here is the code behind for this page.




Public Class WebForm2
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.filesAdapter = New System.Data.SqlClient.SqlDataAdapter
        Me.SqlDeleteCommand1 = New System.Data.SqlClient.SqlCommand
        Me.filesConnection = New System.Data.SqlClient.SqlConnection
        Me.SqlInsertCommand1 = New System.Data.SqlClient.SqlCommand
        Me.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommand
        Me.SqlUpdateCommand1 = New System.Data.SqlClient.SqlCommand
        Me.FilesDataSet1 = New SaveFile.filesDataSet
        CType(Me.FilesDataSet1, System.ComponentModel.ISupportInitialize).BeginInit()
        '
        'filesAdapter
        '
        Me.filesAdapter.DeleteCommand = Me.SqlDeleteCommand1
        Me.filesAdapter.InsertCommand = Me.SqlInsertCommand1
        Me.filesAdapter.SelectCommand = Me.SqlSelectCommand1
        Me.filesAdapter.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "Files", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("file_id", "file_id"), New System.Data.Common.DataColumnMapping("file_name", "file_name"), New System.Data.Common.DataColumnMapping("file_size", "file_size"), New System.Data.Common.DataColumnMapping("file_path", "file_path"), New System.Data.Common.DataColumnMapping("upload_date", "upload_date")})})
        Me.filesAdapter.UpdateCommand = Me.SqlUpdateCommand1
        '
        'SqlDeleteCommand1
        '
        Me.SqlDeleteCommand1.CommandText = "DELETE FROM Files WHERE (file_id = @Original_file_id) AND (file_name = @Original_" & _
        "file_name) AND (file_path = @Original_file_path OR @Original_file_path IS NULL A" & _
        "ND file_path IS NULL) AND (file_size = @Original_file_size OR @Original_file_siz" & _
        "e IS NULL AND file_size IS NULL) AND (upload_date = @Original_upload_date OR @Or" & _
        "iginal_upload_date IS NULL AND upload_date IS NULL)"
        Me.SqlDeleteCommand1.Connection = Me.filesConnection
        Me.SqlDeleteCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_file_id", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "file_id", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlDeleteCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_file_name", System.Data.SqlDbType.VarChar, 100, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "file_name", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlDeleteCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_file_path", System.Data.SqlDbType.VarChar, 100, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "file_path", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlDeleteCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_file_size", System.Data.SqlDbType.VarChar, 10, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "file_size", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlDeleteCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_upload_date", System.Data.SqlDbType.DateTime, 8, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "upload_date", System.Data.DataRowVersion.Original, Nothing))
        '
        'filesConnection
        '
        Me.filesConnection.ConnectionString = "workstation id=DELL;packet size=4096;integrated security=SSPI;data source=DELL;pe" & _
        "rsist security info=False;initial catalog=classes"
        '
        'SqlInsertCommand1
        '
        Me.SqlInsertCommand1.CommandText = "INSERT INTO Files(file_name, file_size, file_path, upload_date) VALUES (@file_nam" & _
        "e, @file_size, @file_path, @upload_date); SELECT file_id, file_name, file_size, " & _
        "file_path, upload_date FROM Files WHERE (file_id = @@IDENTITY)"
        Me.SqlInsertCommand1.Connection = Me.filesConnection
        Me.SqlInsertCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@file_name", System.Data.SqlDbType.VarChar, 100, "file_name"))
        Me.SqlInsertCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@file_size", System.Data.SqlDbType.VarChar, 10, "file_size"))
        Me.SqlInsertCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@file_path", System.Data.SqlDbType.VarChar, 100, "file_path"))
        Me.SqlInsertCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@upload_date", System.Data.SqlDbType.DateTime, 8, "upload_date"))
        '
        'SqlSelectCommand1
        '
        Me.SqlSelectCommand1.CommandText = "SELECT file_id, file_name, file_size, file_path, upload_date FROM Files"
        Me.SqlSelectCommand1.Connection = Me.filesConnection
        '
        'SqlUpdateCommand1
        '
        Me.SqlUpdateCommand1.CommandText = "UPDATE Files SET file_name = @file_name, file_size = @file_size, file_path = @fil" & _
        "e_path, upload_date = @upload_date WHERE (file_id = @Original_file_id) AND (file" & _
        "_name = @Original_file_name) AND (file_path = @Original_file_path OR @Original_f" & _
        "ile_path IS NULL AND file_path IS NULL) AND (file_size = @Original_file_size OR " & _
        "@Original_file_size IS NULL AND file_size IS NULL) AND (upload_date = @Original_" & _
        "upload_date OR @Original_upload_date IS NULL AND upload_date IS NULL); SELECT fi" & _
        "le_id, file_name, file_size, file_path, upload_date FROM Files WHERE (file_id = " & _
        "@file_id)"
        Me.SqlUpdateCommand1.Connection = Me.filesConnection
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@file_name", System.Data.SqlDbType.VarChar, 100, "file_name"))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@file_size", System.Data.SqlDbType.VarChar, 10, "file_size"))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@file_path", System.Data.SqlDbType.VarChar, 100, "file_path"))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@upload_date", System.Data.SqlDbType.DateTime, 8, "upload_date"))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_file_id", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "file_id", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_file_name", System.Data.SqlDbType.VarChar, 100, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "file_name", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_file_path", System.Data.SqlDbType.VarChar, 100, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "file_path", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_file_size", System.Data.SqlDbType.VarChar, 10, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "file_size", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Original_upload_date", System.Data.SqlDbType.DateTime, 8, System.Data.ParameterDirection.Input, False, CType(0, Byte), CType(0, Byte), "upload_date", System.Data.DataRowVersion.Original, Nothing))
        Me.SqlUpdateCommand1.Parameters.Add(New System.Data.SqlClient.SqlParameter("@file_id", System.Data.SqlDbType.Int, 4, "file_id"))
        '
        'FilesDataSet1
        '
        Me.FilesDataSet1.DataSetName = "filesDataSet"
        Me.FilesDataSet1.Locale = New System.Globalization.CultureInfo("en-US")
        CType(Me.FilesDataSet1, System.ComponentModel.ISupportInitialize).EndInit()

    End Sub
    Protected WithEvents filesGrid As System.Web.UI.WebControls.DataGrid
    Protected WithEvents filesAdapter As System.Data.SqlClient.SqlDataAdapter
    Protected WithEvents SqlSelectCommand1 As System.Data.SqlClient.SqlCommand
    Protected WithEvents SqlInsertCommand1 As System.Data.SqlClient.SqlCommand
    Protected WithEvents SqlUpdateCommand1 As System.Data.SqlClient.SqlCommand
    Protected WithEvents SqlDeleteCommand1 As System.Data.SqlClient.SqlCommand
    Protected WithEvents filesConnection As System.Data.SqlClient.SqlConnection
    Protected WithEvents FilesDataSet1 As SaveFile.filesDataSet

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        filesAdapter.Fill(FilesDataSet1)
        If Not IsPostBack Then
            filesGrid.DataSource = FilesDataSet1.Files.DefaultView
            filesGrid.DataKeyField = "file_id"
            filesGrid.DataBind()
        End If

    End Sub

    Private Sub filesGrid_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles filesGrid.SortCommand
        Dim SortView As DataView = FilesDataSet1.Files.DefaultView
        Dim CurrentSort As String = ""
        If Not ViewState("Sort") Is Nothing Then
            CurrentSort = ViewState("Sort")
        End If
        If CurrentSort.StartsWith(e.SortExpression) Then
            If CurrentSort.EndsWith("DESC") Then
                SortView.Sort = e.SortExpression
            Else
                SortView.Sort = e.SortExpression & " DESC"
            End If
        Else
            SortView.Sort = e.SortExpression
        End If
        ViewState("Sort") = SortView.Sort
        filesGrid.DataSource = SortView
        filesGrid.DataBind()
    End Sub

    Private Sub filesGrid_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles filesGrid.DeleteCommand
        FilesDataSet1.Files.Rows.Item(e.Item.ItemIndex).Delete()
        filesAdapter.Update(FilesDataSet1)
        filesGrid.DataSource = FilesDataSet1.Files.DefaultView
        filesGrid.EditItemIndex = -1
        filesGrid.DataBind()
    End Sub
End Class
0
jettman26
Asked:
jettman26
  • 2
  • 2
1 Solution
 
tusharashahCommented:
Make sure that ASPNET Process has proper permission on the folder to Delete/Modify Files and thne modify your Delete Routine like following:


Private Sub filesGrid_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles filesGrid.DeleteCommand

        Dim filePath As String = e.Item.Cells[n].Text               ' Replace n with Column Number of you file_path
        System.IO.File.Delete( Server.MapPath(filePath) )        
        FilesDataSet1.Files.Rows.Item(e.Item.ItemIndex).Delete()
        filesAdapter.Update(FilesDataSet1)
        filesGrid.DataSource = FilesDataSet1.Files.DefaultView
        filesGrid.EditItemIndex = -1
        filesGrid.DataBind()
    End Sub
End Class


-tushar
0
 
jettman26Author Commented:
Thanks
I set the ASPNET to have Full Control on the security tab.
C:\Inetpub\wwwroot\SaveFile\Data\close.ico is a valid directory.  close.ico is a file in C:\Inetpub\wwwroot\SaveFile\Data.
I get the error posted below though.



Server Error in '/SaveFile' Application.
--------------------------------------------------------------------------------

Invalid path for MapPath 'C:\Inetpub\wwwroot\SaveFile\Data\close.ico'. A virtual path is expected.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Invalid path for MapPath 'C:\Inetpub\wwwroot\SaveFile\Data\close.ico'. A virtual path is expected.

Source Error:


Line 140:    Private Sub filesGrid_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles filesGrid.DeleteCommand
Line 141:        Dim filePath As String = e.Item.Cells(3).Text               ' Replace n with Column Number of you file_path
Line 142:        System.IO.File.Delete(Server.MapPath(filePath))
Line 143:        FilesDataSet1.Files.Rows.Item(e.Item.ItemIndex).Delete()
Line 144:        filesAdapter.Update(FilesDataSet1)
 

Source File: C:\Inetpub\wwwroot\SaveFile\WebForm2.aspx.vb    Line: 142

Stack Trace:


[ArgumentException: Invalid path for MapPath 'C:\Inetpub\wwwroot\SaveFile\Data\close.ico'. A virtual path is expected.]
   System.Web.HttpRequest.MapPath(String virtualPath, String baseVirtualDir, Boolean allowCrossAppMapping)
   System.Web.HttpRequest.MapPath(String virtualPath)
   System.Web.HttpServerUtility.MapPath(String path)
   SaveFile.WebForm2.filesGrid_DeleteCommand(Object source, DataGridCommandEventArgs e) in C:\Inetpub\wwwroot\SaveFile\WebForm2.aspx.vb:142
   System.Web.UI.WebControls.DataGrid.OnDeleteCommand(DataGridCommandEventArgs e)
   System.Web.UI.WebControls.DataGrid.OnBubbleEvent(Object source, EventArgs e)
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
   System.Web.UI.WebControls.DataGridItem.OnBubbleEvent(Object source, EventArgs e)
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
   System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   System.Web.UI.Page.ProcessRequestMain() +1292

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.2032; ASP.NET Version:1.1.4322.2032
0
 
tusharashahCommented:
Seems like the file you have in File_Path is full path of the file so modify Delete Routine like following:

Private Sub filesGrid_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles filesGrid.DeleteCommand
        Dim filePath As String = e.Item.Cells(3).Text  
        System.IO.File.Delete( filePath )
        FilesDataSet1.Files.Rows.Item(e.Item.ItemIndex).Delete()
        filesAdapter.Update(FilesDataSet1)
  ---
  ---


-tushar
0
 
jettman26Author Commented:
Thanks
Works great!
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now