简体   繁体   中英

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.

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["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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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