MD Masum
MD Masum

Reputation: 11

delete file form folder that uploaded and path stored in SQL server asp.net

I was upload number of PDF, and i store there path in SQL server. I need to be able to delete pdf file that was saved in a folder. I've managed to get the upload & download working but the delete is baffling me. my code is...`

 protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SqlConnection con = new SqlConnection(cs);
        ProductID = gridView.DataKeys[e.RowIndex].Values["ProductID"].ToString();
        //File Delete start//
        using (SqlConnection con1 = new SqlConnection(cs))
        {
            SqlCommand cmd1 = new SqlCommand("SELECT PDF1, PDF2, PDF3 FROM Product WHERE ProductID = @ProductID", con1);
            cmd1.Parameters.AddWithValue("ProductID", ProductID);

            SqlDataAdapter sda = new SqlDataAdapter(cmd1);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            try
            {
                string pdf1 = dt.Rows[0]["PDF1"].ToString();
                string pdf2 = dt.Rows[0]["PDF2"].ToString();
                string pdf3 = dt.Rows[0]["PDF3"].ToString();

                string strFileFullPath1 = VirtualPathUtility.ToAbsolute(pdf1);
                if (File.Exists(strFileFullPath1))
                {
                    File.Delete(strFileFullPath1);
                }
                string strFileFullPath2 = VirtualPathUtility.ToAbsolute(pdf2);
                if (File.Exists(strFileFullPath2))
                {
                    File.Delete(strFileFullPath2);
                }
                string strFileFullPath3 = VirtualPathUtility.ToAbsolute(pdf3);
                if (File.Exists(strFileFullPath3))
                {
                    File.Delete(strFileFullPath3);
                }
            }

Upvotes: 0

Views: 861

Answers (1)

Damith
Damith

Reputation: 63065

get the absolute path from relative path and then delete the file

string strFileFullPath= Server.MapPath(brangimage);
if (System.IO.File.Exists(strFileFullPath)) {
        System.IO.File.Delete(strFileFullPath);
    }

Upvotes: 1

Related Questions