[英]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.