如何在不删除Asp.net解决方案资源管理器文件夹中的特定文件的情况下删除所有文件?

时间:2014-06-06 11:05:21

标签: c# asp.net

我正在尝试使用这段代码删除除了路径+名称由ViewState保留的特定文件以外的所有文件。

string[] filePaths = Directory.GetFiles(@"E:\Projects\BlockSchemeManagement\Attachment");

foreach (string filePath in filePaths)
         File.Delete(filePath);

此代码应删除所有文件,但不删除任何文件。

这是用于保存此特定文件的viewState:

ViewState["file"] = @parentDir + filename;

任何人都可以建议如何继续吗?

4 个答案:

答案 0 :(得分:3)

如果您的应用程序或任何其他应用程序打开并锁定了文件,则无法将其删除。尝试忽略第一个文件中的异常并删除其他文件。

string[] filePaths = Directory.GetFiles(@"E:\Projects\BlockSchemeManagement\Attachment");

foreach (string filePath in filePaths) 
{
    if (filePath != ViewState["file"])
    {
        try
        {
             File.Delete(filePath);
        } 
          catch { }
    }
}

请注意,ViewState [" file"]应具有文件的全名,例如

E:\项目\ BlockSchemeManagement \附件\ FILENAME.EXT

答案 1 :(得分:0)

您应该检查路径是否存在,如下面的代码以及您要删除的文件不应该在任何地方打开。

if (IO.File.Exists(filePaths )) 
{
       foreach (string filePath in filePaths)
       {
           File.Delete(filePath);
       }
}

和你的

  

如何在不删除特定文件的情况下删除所有文件

问题尝试下面的代码: -

 foreach (string filePath in filePaths)
 {   
    var name = new FileInfo(filePath).Name;
   if (filePath != ViewState["file"])
   {
      try
      {
         File.Delete(filePath);
      } 
      catch { }
   }
}

答案 2 :(得分:0)

检查正在创建和打开此文件的对象。您需要在删除文件之前处置该对象。否则该文件的句柄将由该对象保存。因此,访问被拒绝错误。

答案 3 :(得分:0)

     string[] filePaths = Directory.GetFiles(@"E:\Software Developing\project and project data\LilacInsights\LilacInsights\Pdf\");

            foreach (string filePath in filePaths)
if(filePath != "yourfilename with path")
                System.IO.File.Delete(filePath);

this code run properly , its deleting each file from folder, 

now if u wan to exclude any file from delete jus keep tht file in if condition 
if ()