簡體   English   中英

如何刪除所有文件而不刪除Asp.net解決方案資源管理器文件夾中的特定文件?

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

我正在嘗試這段代碼來刪除所有文件,但路徑+名稱由ViewState保留的特定文件除外。

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

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

此代碼應刪除所有文件,但不刪除任何文件。

這是通過以下方式保留此特定文件的viewState:

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

有人可以建議如何進行嗎?

如果文件是由您的應用程序或任何其他應用程序打開並鎖定的,則無法刪除它。 嘗試忽略第一個文件的異常並刪除其他文件。

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:\\ Projects \\ BlockSchemeManagement \\ Attachment \\ filename.ext

您應按照以下代碼檢查路徑是否存在,以及要刪除的文件不應在任何地方打開。

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 { }
   }
}

檢查正在創建並打開此文件的對象。 您需要在刪除文件之前處理該對象。 否則,該文件的句柄將由該對象保留。 因此,訪問被拒絕錯誤。

     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