C# 删除目录中除文件外的所有内容

发布于 2024-10-29 21:07:17 字数 683 浏览 5 评论 0原文

我在删除目录中除文件(index.dat)之外的所有内容时遇到问题 我试图清除 cookies 文件夹和临时文件夹中的文件,但当我尝试删除 index.dat 时出现错误,因为它被另一个进程使用。有没有办法删除临时和 cookies 文件夹中除 index.dat 文件之外的所有内容?这是我的代码:

string userProfile = Environment.GetEnvironmentVariable("USERPROFILE");
string strDirLocalq = Path.Combine(userProfile, "AppData");
string strDirLocalw = Path.Combine(strDirLocalq, "Roaming");
string strDirLocale = Path.Combine(strDirLocalw, "Microsoft");
string strDirLocalr = Path.Combine(strDirLocale, "Windows");
string strDirLocalt = Path.Combine(strDirLocalr, "Cookies");

string[] filePaths = Directory.GetFiles(strDirLocalt);
foreach (string filePath in filePaths)
    File.Delete(filePath);

I am having trouble deleting everything in a directory except a file (index.dat)
I am trying to clear the cookies folder and the temp folder of files but I get an error when I try to delete index.dat because its being used by another process. Is there a way to delete everything in the temp and cookies folder except the index.dat file? Here is my code:

string userProfile = Environment.GetEnvironmentVariable("USERPROFILE");
string strDirLocalq = Path.Combine(userProfile, "AppData");
string strDirLocalw = Path.Combine(strDirLocalq, "Roaming");
string strDirLocale = Path.Combine(strDirLocalw, "Microsoft");
string strDirLocalr = Path.Combine(strDirLocale, "Windows");
string strDirLocalt = Path.Combine(strDirLocalr, "Cookies");

string[] filePaths = Directory.GetFiles(strDirLocalt);
foreach (string filePath in filePaths)
    File.Delete(filePath);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

甜嗑 2024-11-05 21:07:17

这有效:

string[] filePaths = Directory.GetFiles(strDirLocalt);
foreach (string filePath in filePaths)
{
    var name = new FileInfo(filePath).Name;
    name = name.ToLower();
    if (name != "index.dat")
    {
        File.Delete(filePath);
    }
}

This works:

string[] filePaths = Directory.GetFiles(strDirLocalt);
foreach (string filePath in filePaths)
{
    var name = new FileInfo(filePath).Name;
    name = name.ToLower();
    if (name != "index.dat")
    {
        File.Delete(filePath);
    }
}
沒落の蓅哖 2024-11-05 21:07:17

看看这个有趣的解决方案!

List<string> files = new List<string>(System.IO.Directory.GetFiles(strDirLocalt));
files.ForEach(x => { try { System.IO.File.Delete(x); } catch { } });

感受语言之美!

Check out this interesting solution!

List<string> files = new List<string>(System.IO.Directory.GetFiles(strDirLocalt));
files.ForEach(x => { try { System.IO.File.Delete(x); } catch { } });

Feel the beauty of the language!

晨与橙与城 2024-11-05 21:07:17

只需在 File.Delete 周围放置一个 try/catch,因为可能有更多文件正在使用,这些文件也会引发异常。

try
{
  File.Delete(filePath);
}
catch (Exception ignore)
{
}

Simply place a try/catch around the File.Delete because there could be more files that are in use which will also throw exceptions.

try
{
  File.Delete(filePath);
}
catch (Exception ignore)
{
}
甜柠檬 2024-11-05 21:07:17
string[] filePaths = Directory.GetFiles(strDirLocalt); 
foreach (string filePath in filePaths)
 try {
   File.Delete(filePath);
 }
 catch{ }
}
string[] filePaths = Directory.GetFiles(strDirLocalt); 
foreach (string filePath in filePaths)
 try {
   File.Delete(filePath);
 }
 catch{ }
}
温柔少女心 2024-11-05 21:07:17

只需从列表中过滤即可

foreach (string filePath in filePaths.Where(!filePath.Contains("index.dat"))
    File.Delete(filePath);

Just filter it from the list

foreach (string filePath in filePaths.Where(!filePath.Contains("index.dat"))
    File.Delete(filePath);
魄砕の薆 2024-11-05 21:07:17

一种可能仍然有效的方法是在安全模式下启动,然后为自己分配管理员权限,然后看看是否可以找到文件来删除它们

我现在使用的方法是创建一个批处理文件来重命名该文件夹下面的子文件夹包含index.bat 文件,然后仅将文件夹复制回不包含这些文件的原始位置,但生成的批处理文件需要从具有完全管理员权限的单独 Windows 帐户运行。

One method that might still work is to boot-up in safe mode and then assign yourself administrator rights and then see if you can find the files to delete them

The method I now use is to create a batch file to rename the subfolder below the folder containing the index.bat files and to then only copy the folders back to the original location that don't contain these files but the resultant batch files needs to be run from a separate windows account that has full administrator permissions.

笑饮青盏花 2024-11-05 21:07:17

为什么不直接捕获异常 - 当您尝试删除它们时,任何文件都可能正在使用中。

try{
     // delete
}
catch{
}

Why not just catch the exception - there is the possiblility that any of the files could be in use when you attempt to delete them.

try{
     // delete
}
catch{
}
雪落纷纷 2024-11-05 21:07:17

这是一个递归方法,它删除目录中不包括提供的文件名列表的所有文件:

public static void DeleteAllExcept(string folderPath, List<string> except, bool recursive = true)
{
    var dir = new DirectoryInfo(folderPath);
    
    //Delete files excluding the list of file names
    foreach (var fi in dir.GetFiles().Where(n => !except.Contains(n.Name)))
    {
        fi.Delete();
    }

    //Loop sub directories if recursive == true
    if (recursive)
    {
        foreach (var di in dir.GetDirectories())
        {
            DeleteAllExcept(di.FullName, except, recursive);

            //Delete directory if empty
            if (!di.EnumerateFileSystemInfos().Any())
            {
                di.Delete();
            }
        }
    }
}

因此,您需要编译不想删除的文件列表,然后调用该方法:

string myDir = @"C:\TestDirectory"
List<string> keepFiles = new List<string>();

keepFiles.Add("test.txt");
keepFiles.Add("picture.png");
keepFiles.Add("file.pdf");

DeleteAllExcept(myDir, keepFiles, true);

TestDirectory 的结构如下:

-\
-\test.txt
-\test2.txt
-\test3.txt
-\img\
-\img\picture.png
-\img\banner.png
-\img\temp.jpg
-\files\
-\files\sheet.xls
-\files\file.pdf

因此文件 test2.txttest3.txtbanner.pngtemp.jpg 和 sheet.xls 将被删除。

Here is a recursive method which deletes all files in a directory excluding a list of provided file names:

public static void DeleteAllExcept(string folderPath, List<string> except, bool recursive = true)
{
    var dir = new DirectoryInfo(folderPath);
    
    //Delete files excluding the list of file names
    foreach (var fi in dir.GetFiles().Where(n => !except.Contains(n.Name)))
    {
        fi.Delete();
    }

    //Loop sub directories if recursive == true
    if (recursive)
    {
        foreach (var di in dir.GetDirectories())
        {
            DeleteAllExcept(di.FullName, except, recursive);

            //Delete directory if empty
            if (!di.EnumerateFileSystemInfos().Any())
            {
                di.Delete();
            }
        }
    }
}

So you need to compile a list of files which you do not want to delete and then call the method:

string myDir = @"C:\TestDirectory"
List<string> keepFiles = new List<string>();

keepFiles.Add("test.txt");
keepFiles.Add("picture.png");
keepFiles.Add("file.pdf");

DeleteAllExcept(myDir, keepFiles, true);

The TestDirectory has a structure like:

-\
-\test.txt
-\test2.txt
-\test3.txt
-\img\
-\img\picture.png
-\img\banner.png
-\img\temp.jpg
-\files\
-\files\sheet.xls
-\files\file.pdf

So the files test2.txt, test3.txt, banner.png, temp.jpg and sheet.xls will be deleted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文