如何使用asp.net从文件夹中删除特定文件

Mar*_*ark 16 c# asp.net

这里是我得到了一个被称为gridview1 datagridviewer,当我把它上传更新的文件名和路径,并存储在文件夹"弹匣"上述文件数据库中的gridview1和表格文件的fileupload1交易......但现在我什么想要做的是反过来我得到了如何使用gridview删除表条目但删除文件夹"Mag"无法正常使用C#中的以下代码或代码隐藏

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它给了我错误

"你调用的对象是空的."

请告诉我,我做错了什么是新的,不必深入了解平台所以任何和所有的帮助将不胜感激提前感谢马克

这是我找到的答案感谢Tammy和其他所有人的答案

好的,交易目标函数从gridview和数据库表中删除文件详细信息,并从存储文件的项目文件夹中删除文件

在gridview的脚本部分,你想要包括

OnRowDeleting="FuntionName"
Run Code Online (Sandbox Code Playgroud)

OnSelectedIndexChanged = "FuntionName"
Run Code Online (Sandbox Code Playgroud)

要么

OnRowDeleted="FuntionName"
Run Code Online (Sandbox Code Playgroud)

然后在C#代码(代码隐藏)

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);
       }

     }
  }
Run Code Online (Sandbox Code Playgroud)

只是为那些想要学习的人提供了额外的参考

OnRowDeleting ="FuntionName"就是在删除行之前你可以取消删除或运行数据上的函数,就像我做的那样

它直接删除OnRowDeleted ="FuntionName"

tam*_*tam 45

这是我删除文件的方式

if ((System.IO.File.Exists(fileName)))
                {
                    System.IO.File.Delete(fileName);
}
Run Code Online (Sandbox Code Playgroud)

还要确保您在删除时传递的文件名是准确的路径

编辑

您也可以使用以下事件,或者只使用此代码段中的代码并在您的方法中使用

void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
  {

    // Get the currently selected row using the SelectedRow property.
    GridViewRow row = CustomersGridView.SelectedRow;

    //Debug this line and see what value is returned if it contains the full path.
    //If it does not contain the full path then add the path to the string.
    string fileName = row.Cells[0].Text 

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

     }
  }
Run Code Online (Sandbox Code Playgroud)