Delete File or Caperta in C #

2

I'm trying to delete a file or a complete folder through C #, but I get the following exception.

  

Access denied to path '03 .png '.

My code is as follows:

String tempFolder = @"C:\AdjuntosChat\";
if (Directory.Exists(tempFolder))
{
    File.Delete(tempFolder);
    Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(tempFolder, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
    foreach (var item in Directory.GetFiles(tempFolder, "*.*"))
    {
        File.Delete(item);
    }
}
    
asked by Spyros Capetanopulos 18.04.2017 в 15:16
source

2 answers

0

Try adding this line just before deleting the file:

File.SetAttributes(item, FileAttributes.Normal);

So, according to your code, it looks like this:

foreach (var item in Directory.GetFiles(tempFolder, "*.*"))
{
    File.SetAttributes(item, FileAttributes.Normal);
    File.Delete(item);
}
    
answered by 18.04.2017 / 17:45
source
0

Mainly due to two possible causes:

1) Lack of sufficient permissions to delete the file

Solution: Give permissions on the file (s) for the user that executes your application, normally the write permission allows you to erase, however if you use the extended Windows permissions there is a Delete permission.

Define, view, change or remove file and folder permissions

An easy way (not the most recommended) is to grant Total Control permissions over the entire folder via code would be something like this:

DirectorySecurity sec = Directory.GetAccessControl(path);
// Using this instead of the "Everyone" string means we work on non-English systems.
SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(path, sec);

source: link

2) The file is in use by another process:

Solution :

Make sure that it is not your program that has "grabbed" the file in some other routine: using variables by method, not global, nor by procedures, closing file access streams, etc.

If not, you can see which process has "grabbed" the file with Process Explorer from Sysinternals, following the steps on this page:

How to delete, move or rename files blocked by Windows

Although Process Explorer allows you to release the file, I recommend focusing on finding the reason why it is blocked so that the lock does not repeat and your application is released. The antivirus can be a cause.

    
answered by 18.04.2017 в 17:59