I´m making a program to delete some files that I have on my PC. But when I try to do it, I get some error messages like this:
If you are attempting to access a file, make sure it is not ReadOnly.
Make Sure you have sufficient privileges to access this resource.
Get general Help for this exception.
foreach (string subFich in SubFicheiros)
{
listBox.Items.Add("- Deleting File: " + subFich.Substring(Pasta.Length + 1, subFich.Length - Pasta.Length - 1));
ficheirosEncontrador++;
}
try
{
Directory.Delete(Pasta, true);
}
catch (IOException)
{
Thread.Sleep(0);
//The Message Error appears here on this code right below:
Directory.Delete(Pasta, true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(Pasta, true);
}
}
I would like to get some help with this.
How do i ask the user, to let me get the privilegies to delete it.
Well.. what your code doing is: You're deleting the directory and if it gives any exception then you're again trying to do the same step where you got exception.
First of all error is because files are set to read only or because you dont have enough rights to delete the directory (or probably some process is using the files which you are trying to delete)
foreach (string subFich in SubFicheiros)
{
listBox.Items.Add("- Deleting File: " + subFich.Substring(Pasta.Length + 1, subFich.Length - Pasta.Length - 1));
ficheirosEncontrador++;
}
try
{
var di = new DirectoryInfo(Pasta);
di.Attributes &= ~FileAttributes.ReadOnly;
Directory.Delete(Pasta, true);
}
catch (Exception EE)
{
MessageBox.Show("Error: "+ EE.toString());
}
if this code still doesn't work check if you have admin rights to delete that folder
Sounds like your file is read-only, or you do not have the right to remove the file you want based on your user login.
Related
So my problem is that I want to export my user account.
But inside C:\%user%\AppData\Local\ are System Hardlinks e.g.: Application Data which I obviously have no right to use them.
Is there a way to exclude those System Hardlinks from the copying process?
I'm not sure what you mean with hard links, but this might help you
foreach (var dir in new DirectoryInfo(#"c:\users\xxxxxx\AppData\Local").GetDirectories())
{
if (dir.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
Console.WriteLine(dir.Name + " is symbolic, skip it");
}
else
{
//do your copy here
}
}
So I fixed the issue with Exception handling, doing it this way:
FileInfo[] sourceFiles = null;
try {
sourceFiles = new DirectoryInfo(sourcePath).GetFiles();
} catch (Exception ex) {
WriteLog(LogPath, ex + "");
return;
}
Since I'm a bit new to exception handling, I couldn't work it out for the first few hours on this problem.
At the end of the month I copy a file over to a different location and remove the original:
System.IO.File.Copy(fileLocation + PLU.FolderPath, destinationFilePath, true);
System.IO.File.Delete(PLU.FolderPath);
The file copies but it doesnt remove, it doesnt remove because the file doesnt exist.
PLU.FolderPath holds: PLU_104.DAT, which is why I need to use the 'fileLocation + PLU.FolderPath' in the copy.
Shouldnt it throw an error if it doesnt delete though? Even if the file it is looking for is not there?
I've tried it inside a try catch but it still doesnt throw an error:
System.IO.File.Copy(fileLocation + PLU.FolderPath, destinationFilePath, true);
try
{
System.IO.File.Delete(PLU.FolderPath);
}
catch (Exception e)
{
Log.Quiet("Didnt delete" + e.Message);
}
From Msdn
If the file to be deleted does not exist, no exception is thrown.
http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx
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
I want to move a directory from one location to another using C# .NET. I used Directory.Move or even DirectoryInfo (with MoveTo) this simple way:
// source is: "C:\Songs\Elvis my Man"
// newLocation is: "C:\Songs\Elvis"
try
{
// Previous command was: Directory.Move(source, newLocation);
DirectoryInfo dir = new DirectoryInfo(source);
dir.MoveTo(newLocation);
}
catch (Exception e)
{
Console.WriteLine("Error: "+ e.Message);
}
But action that's being done (for both cases) is renaming the folder name from 'source' to 'newLocation'
What I expected? that folder "Elvis my man" will be now in "Elvis" folder.
What has happened? "Elvis my man" was changed to "Elvis" (Renamed). If the directory "Elvis" is already exists, it can't change it to "Elvis" (cause he can't make a duplicate names), therefore I get an exception saying that.
What am I doing wrong??
Many thanks!!!
I would advise putting validation around the Move command to ensure that the source location does exists and the destination location doesn't exists.
I've always found it easier to avoid the exceptions than handle them once they do occur.
You'll probably want to include exception handling as well, just in case the access permissions are a problem or a file is open and can't be moved...
Here's some sample code for you:
string sourceDir = #"c:\test";
string destinationDir = #"c:\test1";
try
{
// Ensure the source directory exists
if (Directory.Exists(sourceDir) == true )
{
// Ensure the destination directory doesn't already exist
if (Directory.Exists(destinationDir) == false)
{
// Perform the move
Directory.Move(sourceDir, destinationDir);
}
else
{
// Could provide the user the option to delete the existing directory
// before moving the source directory
}
}
else
{
// Do something about the source directory not existing
}
}
catch (Exception)
{
// TODO: Handle the exception that has been thrown
}
Even though this works in the command line to move a file, when programming you need to provide the full new name.
So you'd need to change newLocation to "C:\Songs\Elvis\Elvis my Man" to make this work.
From MSDN,
This method throws an IOException if, for example, you try to move c:\mydir to c:\public, and c:\public already exists. You must specify "c:\public\mydir" as the destDirName parameter, or specify a new directory name such as "c:\newdir".
It looks like you need to set newLocation to C:\Songs\Elvis\Elvis my man
private void moveDirectory(string fuente,string destino)
{
if (!System.IO.Directory.Exists(destino))
{
System.IO.Directory.CreateDirectory(destino);
}
String[] files = Directory.GetFiles(fuente);
String[] directories = Directory.GetDirectories(fuente);
foreach (string s in files)
{
System.IO.File.Copy(s, Path.Combine(destino,Path.GetFileName(s)), true);
}
foreach(string d in directories)
{
moveDirectory(Path.Combine(fuente, Path.GetFileName(d)), Path.Combine(destino, Path.GetFileName(d)));
}
}
Not quite sure why I can't get this file to delete. I'm logged in as Admin, tried "Run as Admin", tried running in the same folder, tried setting permissions on the file, tried creating a test 1.txt file to delete and no luck. It is acting like the file isn't there. I can see it in Windows Explorer. Please any help is welcome. Thank you for your time.
public void deleteFile(string FileToDelete)
{
//sets system32 to system32 path
string system32 = Environment.SystemDirectory + #"\";
//File.SetAttributes(#system32 + FileToDelete, FileAttributes.Normal);
try
{
//check if file exists
if (!File.Exists(#system32 + #FileToDelete))
{
//if it doesn't no need to delete it
Console.WriteLine("File doesn't exist or is has already been deleted.");
//Console.WriteLine(system32 + FileToDelete);
} //end if
//if it does, then delete
else
{
File.Delete(system32 + FileToDelete);
Console.WriteLine(FileToDelete + " has been deleted.");
} //end else
} //end try
//catch any exceptions
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
} //end catch
} //end DeleteFile
I created a test file "test.txt" and it worked no problem. I should not that I didn't use the method you posted, but rather used the contents of your supplied method and used them within the main() method of a console application.
ou should also add ReadLine() to display any messages that are returned.
This is what I used, not that it's much different from what you supplied. If this code doesn't work for you then it must be a system privileged issue.
static void Main(string[] args)
{
string FileToDelete = "test.txt";
//sets system32 to system32 path
string system32 = Environment.SystemDirectory + #"\";
try
{
//check if file exists
if (!File.Exists(system32 + FileToDelete))
{
//if it doesn't no need to delete it
Console.WriteLine("File doesn't exist or is has already been deleted.");
//Console.WriteLine(system32 + FileToDelete);
Console.ReadLine();
} //end if
//if it does, then delete
else
{
File.Delete(system32 + FileToDelete);
Console.WriteLine(FileToDelete + " has been deleted.");
Console.ReadLine();
} //end else
} //end try
//catch any exceptions
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
Console.ReadLine();
} //end catch
}
Try this one out
check if file exist on 64 bits system using File.Exists
If you're using Vista / Windows 7, maybe you're running into file virtualization issues. Have you tried adding a manifest with a <requestedExecutionLevel level="requireAdministrator"/> line in it ?