简体   繁体   English

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

[英]How to delete all files without deleting a specific file in Asp.net solution explorer's folder?

I am trying this piece of code to delete all files except a particular file whose path+name is hold by a ViewState. 我正在尝试这段代码来删除所有文件,但路径+名称由ViewState保留的特定文件除外。

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

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

This code should delete all files but it is not deleting any of them. 此代码应删除所有文件,但不删除任何文件。

This is the viewState to keep this particular file by the way: 这是通过以下方式保留此特定文件的viewState:

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

Can any one give suggestion how to proceed? 有人可以建议如何进行吗?

If file is opened and locked by your application or by any other application then you cannot delete it. 如果文件是由您的应用程序或任何其他应用程序打开并锁定的,则无法删除它。 Try to ignore the exception on first file and delete other files. 尝试忽略第一个文件的异常并删除其他文件。

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

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

Note that ViewState["file"] should have full name of file such as 请注意,ViewState [“ file”]应该具有文件的全名,例如

E:\\Projects\\BlockSchemeManagement\\Attachment\\filename.ext E:\\ Projects \\ BlockSchemeManagement \\ Attachment \\ filename.ext

you should check if the path exists or not as below code as well as the file whichs you want to delete should not be opened anywhere. 您应按照以下代码检查路径是否存在,以及要删除的文件不应在任何地方打开。

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

and for your 为了你

How to delete all files without deleting a specific file 如何删除所有文件而不删除特定文件

question try below code :- 问题尝试下面的代码:-

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

Check for the object which is creating and opening this file. 检查正在创建并打开此文件的对象。 You need to dispose that object before deleting the file. 您需要在删除文件之前处理该对象。 Otherwise the handle of that file will be hold by that object. 否则,该文件的句柄将由该对象保留。 Hence, access denied error. 因此,访问被拒绝错误。

     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 ()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM