I have the following code and I am trying to delete a folder it works most of the time but occasionally I get an IOException and visual studio says "access denied" The path exist and the folder says it is empty, and no subfolders but I can not delete it using the following code. Any suggestion why this would work most of the time but not always and how to fix it
if ( Directory.Exist( dir2 + "\\Inv")
{
System.IO.DirectoryInfo dirinv = new System.IO.DirectoryInfo(dir2 + "\\Inv");
setAttributesNormal(dirinv);
try
{
Directory.Delete(dir2 + "\\Inv", true);
}
catch (IOException)
{
Directory.Delete(dir2 + "\\Inv", true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(dir2 + "\\Inv", true);
}
}
}
private void setAttributesNormal(DirectoryInfo dir)
{
foreach (var subDir in dir.GetDirectories())
setAttributesNormal(subDir);
foreach (var file in dir.GetFiles())
{
file.Attributes = FileAttributes.Normal;
}
}
Run the program (or if running in Visual Studio, then Visual Studio) by File Explorer Run as Administrator by right clicking on the app.
Visual Studio does not run as admin when one launches it. One must run it with elevated privlidges to do such operations on protected folders or to have access to the ports such as running IE Express from Visual Studio.
Related
I'm trying to create a program that runs through all the drives on a pc and lists the files.
I have 9 drives in my pc and the program runs fine and lists files on all of them except on the drive from which I'm running the program from. (Doesn't matter which drive.)
I have a recursive function that takes all the files and directories it finds and compiles a list.
The function runs fine on all other drives but for the one from which I'm running the program from it says Could not find file 'D:\CreateFileList.deps.json'. and then crashes into catch() for that drive.
Here's the part of the code that does that.
static void DirSearch(string sDir, string file)
{
try
{
// Get files from root of the drive
if ( firstPass == 1 )
{
foreach (string f in Directory.GetFiles(sDir))
{
if (CheckExclusion(f))
{
WriteToFile(f, file);
}
}
firstPass = 0;
}
// Get files recursively
foreach (string d in Directory.GetDirectories(sDir))
{
if (CheckExclusion(d))
{
foreach (string f in Directory.GetFiles(d))
{
if (CheckExclusion(f))
{
WriteToFile(f, file);
}
}
}
DirSearch(d, file);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
Obviously this file is not at the root of the drive but in the same directory as the .exe file.
Does anyone have any idea what might be wrong? Do I have some settings wrong or includes or what?
You need to look at the actual exception being returned. It will give you a hint as to what is happening.
For example if the OS is throwing UnauthorizedAccessException your process is not running as admin and will not be allowed to look at the directory/files.
You need to handle (catch) each of the exceptions listed at Directory.GetDirectories in your try catch.
By handling all (or just the most likely) exceptions, you will be able to have a working program.
I need to search few files under C:\windows folder but I am getting error on lots of folders like "Access denied".
I am admin on the system and I also tried running visual studio as administrator but nothing helped.
here is my code...
var exes = File.ReadAllLines("ListOfExes.txt");
var output = new Dictionary<string, string>();
var sb = new StringBuilder();
var seachLocation = #"c:\windows";
FileIOPermission FilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, seachLocation);
try
{
FilePermission.Demand();
FilePermission.Assert();
foreach (var exe in exes)
{
string[] files = Directory.GetFiles(seachLocation, exe.Trim(), SearchOption.AllDirectories);
if (files.Length > 0 && !output.ContainsKey(exe.Trim()))
{
foreach (var f in files)
Console.WriteLine(f);
}
}
CodeAccessPermission.RevertAssert();
}
catch (SecurityException)
{
Console.WriteLine("You do not have permission to read this directory.");
}
my code works fine on any other folder except windows one.
If I go to the path for access denied using windows explorer then it gave me a prompt for access and if I click on continue then it let me go inside the folder.
I understand this is happening because security design but is there any way to make search in entire windows folder if I have admin rights.
I need to use the code as I have thousands of file to search and note their path in windows directory.
Hi i am actually creating a program to delete all the temp files and folders when an event is triggered. so for that i am using the following code but its not working and throwing an exception
And also for this i am using the code
private void tempfiles_Click(object sender, EventArgs e)
{
if(tempcheck.Checked)
{
string tempPath = System.IO.Path.GetTempPath();
System.IO.DirectoryInfo di = new DirectoryInfo(tempPath);
try
{
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
catch(Exception env)
{
MessageBox.Show("Please close all the applications and try \n" + env);
}
}
else
{
MessageBox.Show("Please check the checkbox");
}
}
Here i want to delete the folders and files without any exception but in java i use method like fileonclose().
If files are being used by another program, you will not be able to delete them. You should put your try...catch statement inside each for loop. That way you can continue trying to delete files even if one attempt fails.
To make your program more useful, you can keep track of which files were not deleted and create a log or open a window to show the file names to the user.
I need to delete all internet explorer cached files from my application, this is my code:
void clearIECache()
{
ClearFolder(
new DirectoryInfo(
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)));
}
void ClearFolder(DirectoryInfo folder)
{
foreach (FileInfo file in folder.GetFiles())
{
try
{
file.Delete();
}
catch (Exception)
{
}
}
}
It says that I have no authorization to delete files, I tried to delete files in that folder from console and it gives the same error...
Is there another way to clear explorer cache ?
I'm trying to iterate over the items on my start menu, but I keep receiving the UnauthorizedAccessException. I'm the directory's owner and my user is an administrator.
Here's my method (it's in a dll project):
// root = C:\Users\Fernando\AppData\Roaming\Microsoft\Windows\Start Menu
private void walkDirectoryTree(DirectoryInfo root) {
try {
FileInfo[] files = root.GetFiles("*.*");
foreach (FileInfo file in files) {
records.Add(new Record {Path = file.FullName});
}
DirectoryInfo[] subDirectories = root.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories) {
walkDirectoryTree(subDirectory);
}
} catch (UnauthorizedAccessException e) {
// do some logging stuff
throw; //for debugging
}
}
The code fail when it starts to iterate over the subdirectories. What else should I do? I've already tried to create the manifest file, but it didn't work.
Another point (if is relevant): I'm just running some unit tests with visual studio (which is executed as administrator).
Based on your description, it appears there is a directory to which your user does not have access when running with UAC enabled. There is nothing inherently wrong with your code and the behavior in that situation is by design. There is nothing you can do in your code to get around the fact that your account doesn't have access to those directories in the context it is currently running.
What you'll need to do is account for the directory you don't have access to. The best way is probably by adding a few extension methods. For example
public static FileInfo[] GetFilesSafe(this DirectoryRoot root, string path) {
try {
return root.GetFiles(path);
} catch ( UnauthorizedAccessException ) {
return new FileInfo[0];
}
}