How to delete a specific file from folder using asp.net
<p>here's the deal I got a datagridviewer which is called gridview1 and a fileupload1 when i upload a file it updates the gridview1 and table in database with the file name and path and stores the said file in folder "Mag"... but now what i want to do is the reverse i got how to use the gridview to delete the table entry but deleting the file from folder "Mag" is not working have used the following code in C# or codebehind</p>

<pre><code>protected void GridView1_Del(object sender, EventArgs e)  
{
    string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
    string[] Files = Directory.GetFiles(@"i:/Website/WebSite3/Mag/");

    foreach (string file in Files)
    {
        if (file.ToUpper().Contains(DeleteThis.ToUpper()))
        {
            File.Delete(file);
        }
    }
}
</code></pre>

<p>it gives me error </p>

<blockquote>
  <p>"Object reference not set to an instance of an object." </p>
</blockquote>

<p>pls tell me what im doing wrong am new and don't have to in depth understanding of the platform so any and all help will be appreciated
thanks in advance
Mark </p>

<p>Here is the answer i found Thanks Tammy and everyone else for all the answers</p>

<p>Ok  here the deal target function delete file details from gridview and database table and file from project folder where the file is stored </p>

<p>in script section of gridview you would want to include</p>

<pre><code>OnRowDeleting="FuntionName"
</code></pre>

<p>Not</p>

<pre><code>OnSelectedIndexChanged = "FuntionName"
</code></pre>

<p>or</p>

<pre><code>OnRowDeleted="FuntionName"
</code></pre>

<p>then in C# code(codebehind)</p>

<pre><code>protected void FuntionName(object sender, GridViewDeleteEventArgs e)
    {
// storing value from cell
        TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];

// full path required
        string fileName = ("i:/Website/WebSite3/Mag/" + cell.Text); 

    if(fileName != null || fileName != string.Empty)
    {
       if((System.IO.File.Exists(fileName))) 
       {
           System.IO.File.Delete(fileName);
       }

     }
  }
</code></pre>

<p>And just for added reference for those who want to learn</p>

<p>OnRowDeleting="FuntionName" is for just before deleting a row you can cancel deleting or run funtions on the data like i did</p>

<p>OnRowDeleted="FuntionName" it directly deletes</p>
