从目录 asp.net 中删除文件 c#

Delete File from Directory asp.net c#

我正在显示站点上目录的图像,用户可以上传和删除该文件夹的内容。但是,出于某种原因,我的删除 link 按钮不起作用。 这是我显示图像的代码(没有问题):

{
            string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/Products/"));
            List<String> images = new List<string>(filesindirectory.Count());

            foreach (string item in filesindirectory)
            {
                images.Add(String.Format("~/Images/Products/{0}", System.IO.Path.GetFileName(item)));
            }
            ListView1.DataSource = images;
            ListView1.DataBind();
        }

这是删除 Link 按钮的代码(这不起作用):

protected void deleteLinkButton_Click(object sender, EventArgs e)
    {
        var deleteButton = sender as LinkButton;
        string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/Products/{0}"));
        try
        {
            FileInfo fi = new FileInfo(Server.MapPath("~/Images/Products/"));
            fi.Delete();
            statusLabel2.Text = "Delete Image Successful!";
        }
        catch
        {
            // Display error
            statusLabel2.Text = "Delete Image Failed";
        }
        ListView1.DataBind();
    }

当我尝试删除文件时收到此错误消息: System.IO.DirectoryNotFoundException: 找不到部分路径

我的堆栈跟踪显示:

System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +359 System.IO.FileSystemEnumerableIterator1.CommonInit() +268 System.IO.FileSystemEnumerableIterator1..ctor(字符串路径,字符串 originalUserPath,字符串 searchPattern,SearchOption searchOption,SearchResultHandler`1 resultHandler,Boolean checkHost)+445 System.IO.Directory.GetFiles(字符串路径)+70

您指定了无效的搜索路径 "~/Images/Products/{0}",这给了您错误 - 不确定应该是什么。

您正在尝试将目录作为文件删除 - 因此下一个错误将出现在这一行:

FileInfo fi = new FileInfo(Server.MapPath("~/Images/Products/"));
fi.Delete()
FileInfo fi = new FileInfo(Server.MapPath("~/Images/Products/"));

这里你尝试初始化一个目录作为文件

string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/Products/{0}"));

这里你有一个无效的目录路径 - 这个会抛出你的异常