【问题标题】:delete all files in local path删除本地路径中的所有文件
【发布时间】:2016-08-03 02:54:57
【问题描述】:
我需要删除我的软件本地路径中的所有文件,除了我的软件
我的脚本:
string a = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Array.ForEach(Directory.GetFiles(a), File.Delete);
错误:
“System.UnauthorizedAccessException”类型的未处理异常
发生在 mscorlib.dll 中
附加信息:L'accès au chemin d'accès
'D:\FWeb\AutoUpdate\AutoUpdate\bin\Debug\AutoUpdate.exe' est refusé.
【问题讨论】:
标签:
c#
visual-studio
delete-file
【解决方案1】:
您正在尝试删除正在使用的文件 - 很可能是当前进程的可执行文件。您可以跳过此特定文件,但请注意,如果它加载任何库(.dll 文件),它们也可能被锁定。其他文件也可能正在使用中(例如 .pdb 文件、资源等),因此请确保排除所有此类文件。
var assemblyPath = Assembly.GetEntryAssembly().Location;
var pathsToExclude = new[] { assemblyPath };
string a = System.IO.Path.GetDirectoryName(assemblyPath);
foreach (var file in Directory.EnumerateFiles(a).Except(pathsToExclude))
File.Delete(file);
【解决方案2】:
您只需要过滤掉您自己的程序集。当然,您不能删除当前正在运行的二进制文件,因此请将其从列表中排除:
string location = Assembly.GetEntryAssembly().Location;
string a = System.IO.Path.GetDirectoryName(location);
string[] files = Directory.GetFiles(a).Where(f => f != location).ToArray();
Array.ForEach(files, File.Delete);
为了避免区分大小写的问题,您可以考虑
string[] files = Directory.GetFiles(a)
.Where(f => !f.Equals(location, StringComparison.OrdinalIgnoreCase))
.ToArray();
改为。