【问题标题】:delete all files in a web directory删除 web 目录中的所有文件
【发布时间】:2014-04-06 06:48:34
【问题描述】:

我有一个包含文件的 Web 目录,我想将它们全部删除。我在网上看过,但所有答案都依赖于文件系统,我想使用网站的目录。我试过这个:

foreach (string file in HttpContext.Current.Server.MapPath("\\MyDirectory"))
{
     File.Delete(file);
}

foreach语句带下划线,错误为'cannot convert type char to string'.

删除目录中所有文件的语法是什么?

谢谢。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    Server.MapPath 为您提供目录路径,而不是文件/文件夹数组。如果您想删除文件夹中的所有文件,您可以这样做:

    var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
    foreach (string file in Directory.GetFiles(folderPath))
    {
        File.Delete(file);
    }
    

    如果你想删除文件夹,那么

    var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
    Directory.Delete(folderPath);
    

    删除主文件夹中的所有文件夹

    var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
    foreach (string file in Directory.GetDirectoriesfolderPath))
    {
        File.Delete(file);
    }
    

    【讨论】:

      【解决方案2】:

      您可能需要更正 MapPath 参数 (\\MyDirectory),但您需要的语法如下所示。

      System.IO.DirectoryInfo di= new DirectoryInfo(HttpContext.Current.Server.MapPath("\\MyDirectory"));
      
      foreach (FileInfo file in di.GetFiles())
      {
        file.Delete(); 
      }
      

      【讨论】:

      • 好的,谢谢;你的回答帮助我重写了我的代码:Array.ForEach(Directory.GetFiles(HttpContext.Current.Server.MapPath("\\MyDirectory")), File.Delete);
      猜你喜欢
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      相关资源
      最近更新 更多