How to delete files from folder

ERROR:Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\Hospital\uploads\bloodman.png'.

public void show_data()
{
    DirectoryInfo d = new DirectoryInfo(Server.MapPath(@"~\Hospital\uploads"));
    FileInfo[] r = d.GetFiles();
    DataTable dt = new DataTable();
    dt.Columns.Add("path");

    for (int i = 0; i < r.Length; i++)
    {
        DataRow row = dt.NewRow();
        row["path"] = "~/Hospital/uploads/"+ r[i].Name;
        dt.Rows.Add(row);
    }

    DataList1.DataSource = dt;
    DataList1.DataBind();
}

protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    File.Delete(e.CommandArgument.ToString());
    Response.Write("File Deleted");
    show_data();
}

1 answer

  • answered 2018-04-17 05:25 Adrian

    Use Server.MapPath('~/') to get the root path of your web-app. Calling"~/Hospital/uploads/" will lead to the file "C:\Program Files (x86)\IIS Express\" the IIS folder which is used to run your app.

    You can do something like this.

     Server.MapPath("~/Hospital/uploads/" + r[i].Name);
    

    Use this method to delete the file. https://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx