C# delete all the things inside the file - c#

I'm trying to delete some files from a specific directory. But there are some errors.
I want my program to ignore these problems.
string[] myFiles = Directory.GetFiles(#"C:\Windows\prefetch");
foreach (string f in myFiles)
{
File.Delete(f);
}

By "errors" you mean thrown exceptions? Directory.GetFiles and File.Delete will throw exceptions if they can't find the directory/file or if you dont have permissions to access it, etc.
Since you want them ignored, you can just catch them and ignore them.
try
{
string[] myFiles = Directory.GetFiles(#"C:\Windows\prefetch");
foreach (string f in myFiles)
{
File.Delete(f);
}
}
catch (Exception)
{
//do nothing
}

use this and you will delete the entire directory and respective files recursively
Directory.Delete(#"C:\Windows\prefetch", true);

Related

Get the exception folder to a listbox C#

I'm creating a method to handle directory and file exceptions.
I have listed all the directories and subdirectories of the C: \ Users \ folder
listBox1.Items.AddRange(Directory.GetDirectories("C:\\Users\\", "*", SearchOption.AllDirectories));
Some folders are protected by windows, and when you run a command for those folders it gives us an exception.
If there is any possible, How can I save the folder that returned the exception to a listbox when the exception happens? thanks
If you catch the Exception the Message will tell you the folder that threw the exception in the format of
Access to the path 'C:\Users\SomeFolder' is denied.
you just need to remove the static text, the simplest way is(you maybe able to find a more stylish way to do this, but you get the idea):
try
{
listBox1.Items.AddRange(Directory.GetDirectories("C:\\Users\\", "*", SearchOption.AllDirectories));
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
SomeListBox.Items.Add(ex.Message.Replace("Access to the path '", "").Replace("' is denied.", ""));
}
EDIT: if you want to traverse all the folders and keep going you might want to take a look at recursion. you could slightly modify the above code to make it a function.
void getDirectories(string path)
{
try
{
string[] directories = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
listBox1.Items.AddRange(directories);
foreach(string directory in directories)
{
getDirectories(directory);
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
SomeListBox.Items.Add(ex.Message.Replace("Access to the path '", "").Replace("' is denied.", ""));
}
}
In case you want all folders with exceptions:
You can use the method with the following call:
List<DirectoryInfo> list = GetDirectories(new DirectoryInfo(#"root directory"), 0, 2);
I've implemented a max level, because in a deep structure it could take a long time before the search is done. If you don't need it, just remove the unnecessary lines of code ;)
List<DirectoryInfo> GetDirectories(DirectoryInfo di, int level, int maxLevel)
{
List<DirectoryInfo> exceptionList = new List<DirectoryInfo>();
foreach (DirectoryInfo directoryInfo in di.GetDirectories("*", SearchOption.TopDirectoryOnly))
{
try
{
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
if (level + 1 < maxLevel)
{
exceptionList.AddRange(GetDirectories(directoryInfo, level + 1, maxLevel));
}
}
catch (UnauthorizedAccessException)
{
exceptionList.Add(directoryInfo);
}
}
return exceptionList;
}

Delete path that is longer than 256 characters using DirectoryInfo.Delete(true) method in c#

My Goal is to use Delete the entire folder and everything inside of that folder that is older than month. Following is code that i wrote:
foreach (String dir in Directory.EnumerateDirectories(args[0]))
{
foreach (String subDir in Directory.EnumerateDirectories(dir))
{
DirectoryInfo dirInfo = new DirectoryInfo(subDir);
if (dirInfo.CreationTime < DateTime.Today.AddMonths(-1))
{
try
{
dirInfo.Delete(true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Isssue: dirInfo.Delete(true) statement throws an exception when path is longer than 256 characters, and does not delete the folder. How can i over come that?
Thank you
You could try moving the folder first to a shorter directory path first so its path is no longer as long, and then deleting it.
dirInfo.MoveTo("C:\temp");
dirInfo.Delete(true);

UnauthorizedAccessException with getDirectories

Hello everyone I currently got subdirectories I wanted through this call:
foreach (DirectoryInfo dir in parent)
{
try
{
subDirectories = dir.GetDirectories().Where(d => d.Exists == true).ToArray();
}
catch(UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
}
foreach (DirectoryInfo subdir in subDirectories)
{
Console.WriteLine(subdir);
var temp = new List<DirectoryInfo>();
temp = subdir.GetDirectories("*", SearchOption.AllDirectories).Where(d => reg.IsMatch(d.Name)).Where((d => !d.FullName.EndsWith("TESTS"))).Where(d => !(d.GetDirectories().Length == 0 && d.GetFiles().Length == 0)).Where(d => d.GetFiles().Length > 3).ToList();
candidates.AddRange(temp);
}
}
foreach(DirectoryInfo dir in candidates)
{
Console.WriteLine(dir);
}
so now my issue is that my final list called candidates I get nothing because im getting an access issue due to one of the folders called lost+found in my subdirectories folder in the try block. I tried using try and catch to handle the exception so I could keep doing my checks I actually dont care about this folder and im trying to just ignore it but I'm not sure how to go about ignoring it out of my get directories search any thoughts? I already tried doing a filter with .where to ignore any folder that contained the folder name but that didnt work either it just stopped my program at the folder name.
I have the same question (ResourceContext.GetForCurrentView call exception) about this exception (UnauthorizedAccessException), and this link gives an answer to the reason why this happens:
http://www.blackwasp.co.uk/FolderRecursion.aspx
Short quote:
... Key amongst these is that some of the folders that you attempt to
read could be configured so that the current user may not access them.
Rather than ignoring folders to which you have restricted access, the
method throws an UnauthorizedAccessException. However, we can
circumvent this problem by creating our own recursive folder search
code. ...
solution:
private static void ShowAllFoldersUnder(string path, int indent)
{
try
{
foreach (string folder in Directory.GetDirectories(path))
{
Console.WriteLine("{0}{1}", new string(' ', indent), Path.GetFileName(folder));
ShowAllFoldersUnder(folder, indent + 2);
}
}
catch (UnauthorizedAccessException) { }
}
You can use recursion like Microsoft explains: link.

Can not delete files from Recent folder

I am writing a Software that can delete Temporary files, Prefetch data, files in Recent folder and so on. My problem is I can delete files from Temp folder successfully, but when I try for Recent folder, an exception is thrown, "Access to path...is denied".
PS: According to some other questions, I have set File attributes to normal, but still no luck. Please help me on this issue. For your better understand, I put some code here:
public Boolean CleanRecentData()
{
isAllClean = true;
String SysRecentPath = System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\Recent";
DirectoryInfo SysRecDir = new DirectoryInfo(SysRecentPath);
File.SetAttributes(SysRecentPath, FileAttributes.Normal);
foreach (FileInfo fi in SysRecDir.GetFiles()) //Access Denied
//Exception is thrown here
{
try
{
fi.Delete();
}
catch (Exception ex)
{
recentLogLines.AppendLine(ex.Message);
isAllClean = false;
}
}
foreach (DirectoryInfo dir in SysRecDir.GetDirectories())
{
try
{
dir.Delete(true);
}
catch (Exception ex)
{
recentLogLines.AppendLine(ex.Message);
isAllClean = false;
}
}
return isAllClean;
}
Are you able to access the Recent folder via Windows Explorer?
You could go ahead and change the permissions in your system, but NOT in your users systems.
Therefore you could handle this exception condition in two ways.
You need to check if you have file access before accessing, using FileIOPermission but this might be redundant and wasteful if you are doing it on too many files.
Just try to open the file and put your effort into a good exception handler if it fails
Reference

foreach loop finally

I have a foreach loop that has try catch and finally. it goes through files in a folder and finally deletes them all....but now if i have two files, as it is deleting all( i need to delete all because of app functionality) it will not go though second file. is it possible to let foreach loop finish then delete all files in foreach method here is an example:
foreach (DirectoryInfo directory in directories)
{
foreach (FileInfo file in directory.GetFiles("*.csv"))
{
try
{
//do something with file
}
catch (Exception e)
{
//catch exception
}
finally
{
if (!IsFileLocked(file))
{
string[] files = Directory.GetFiles(#"C:\Test");
foreach (string filetoDelete in files)
{
File.Delete(filetoDelete);
}
}
}
}
}
hope it is clear enough.
Your code:
Loops through given set of directories and for each of them:
Gets "*.csv" files in that dir and with each file:
Does something and then:
Deletes files from "C:\Test".
Shouldn't you be deleting the file you just processed, or at least files from the dir you are currently processing, not files from "C:\Test"?
I'm not very sure if I'm right understood what you're asking for, but to me it seems solution pretty trivial, like this:
foreach (DirectoryInfo directory in directories)
{
foreach (FileInfo file in directory.GetFiles("*.csv"))
{
try
{
//do something with file
}
catch (Exception e)
{
//catch exception
}
}
foreach(FileInfo fileToDeleteInfo...)
{
try
{
if (!IsFileLocked(fileToDeleteInfo))
{
string[] files = Directory.GetFiles(#"C:\Test");
foreach (string filetoDelete in files)
{
File.Delete(filetoDelete);
}
}
}
catch(...)
{... }
}
In other words, move file deletion from the second (nested) foreach into the new one.
If this is not what you're asking for, please clarify.

Categories