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 ?
Related
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.
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.
My console application program is creating some runtime files while it is working so what I want to do is delete all of these files on the application startup. I have tried this:
public static void Empty(string targetDir)
{
var directory = new DirectoryInfo(targetDir);
if (!directory.Exists) return;
foreach (var file in directory.GetFiles()) file.Delete();
foreach (var subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
...just to look for all the files/folders in the given path (which is in a subdirectory in the program execution path) then delete them. However, I get the following exception:
Access to the path 'file' is denied.
I tried to run the program as administrator with no luck; However, I want a solution that works without using administrator privileges.
Notes :
The file is not running in another application.
The file is not in a protected folder.
The file can be deleted manually with no problems and that's why i
am here.
I got this error and found that it was because my test files were readonly. Changed this and I can now use fileinfo to delete them no worries.
if (File.Exists(filePath))
{
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
You say that the files are not open in another application, but it must be open within your application:
//Create some directories to delete
Directory.CreateDirectory("C:/Temp/DeleteMe");
Directory.CreateDirectory("C:/Temp/DeleteMe/DeleteMe");
File.Create("C:/Temp/DeleteMe/DeleteMeFile");//FileStream still open!!
//Delete the files
var directory = new DirectoryInfo("C:/Temp/DeleteMe");
if (!directory.Exists) return;
foreach (FileInfo file in directory.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in directory.GetDirectories())
{
dir.Delete(true);
}
Make sure you dispose the file stream when you create the file
//Create some directories to delete
Directory.CreateDirectory("C:/Temp/DeleteMe");
Directory.CreateDirectory("C:/Temp/DeleteMe/DeleteMe");
using (File.Create("C:/Temp/DeleteMe/DeleteMeFile")) { }
//Delete the files
var directory = new DirectoryInfo("C:/Temp/DeleteMe");
if (!directory.Exists) return;
foreach (FileInfo file in directory.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in directory.GetDirectories())
{
dir.Delete(true);
}
Try using the Microsoft.VisualBasic.FileIO.FileSystem methods as it has a handy DeleteDirectory method, I had access troubles awhile ago and this was the fix for my problem.
var directory = new DirectoryInfo(targetDir);
if (directory.Exists)
{
Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(targetDir, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
}
Using Windows API MoveFileEx might be a potential solution with a parameter MOVEFILE_DELAY_UNTIL_REBOOT to remove the file only after reboot.
Please check http://msdn.microsoft.com/en-us/library/aa365240%28v=vs.85%29.aspx.
I am trying to unzip a downloaded file with Ionic.Zip Dll.
My code works in a windows application but it wont work in my Web application.
The code runs with no errors but when i check the folder there is still the Ziped downloaded file with no extractions.
Is there any specificity things a web application needs to do this??
private void MyExtract()
{
string zipToUnpack = "C:\\Users\\Shaun\\Desktop\\RescommTestData\\downloadfile.zip";
string unpackDirectory = "ExtractedFiles"; //used to create a file to extract files to
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
// here, we extract every entry, but we could extract conditionally
// based on entry name, size, date, checkbox status, etc.
foreach (ZipEntry e in zip1)
{
e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
// e.Extract(ExtractExistingFileAction.OverwriteSilently);
}
}
try
{
//File.Delete("C:\\Users\\Shaun\\Desktop\\downloadfile.zip");
MessageBox.Show("Unpacked photos and data file into ExtractedFiles folder in bin/Debug");
}
catch (Exception)
{
MessageBox.Show("Could not delete ZIP!");
Environment.Exit(1);
}
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];
}
}