Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnauthorizedAccessException trying to delete a file in a folder where I can delete others files with the same code

Tags:

I'm getting a Unauthorized Access Exception

  • in a file which I can delete manually.
  • in a folder where I'm able to delete by code other files
  • and the file isn't marked as read only
  • besides, I'm using Windows XP in a standalone PC and I have not assigned any permissions to the folder or the file.
  • no other process is using the file

If it helps, this is the code where the exception ocurrs:

protected void DeleteImage(string imageName) {     if (imageName != null)     {         string f = String.Format("~/Images/{0}", imageName);         f = System.Web.Hosting.HostingEnvironment.MapPath(f);         if (File.Exists(f))         {             if (f != null) File.Delete(f);         }     } } 

Why could this happen?

like image 230
eKek0 Avatar asked Jul 21 '09 04:07

eKek0


People also ask

Which function is used to delete file from directory?

Use the rm command to remove files you no longer need. The rm command removes the entries for a specified file, group of files, or certain select files from a list within a directory.

How do I delete a file in Filepath?

File deleteFile = new File(s. getFilepath()); boolean delete = deleteFile. delete();


1 Answers

I encountered the same problem, and found that writing my own Directory.Delete wrapper fixed it up. This is recursive by default:

using System.IO;  public void DeleteDirectory(string targetDir) {     File.SetAttributes(targetDir, FileAttributes.Normal);      string[] files = Directory.GetFiles(targetDir);     string[] dirs = Directory.GetDirectories(targetDir);      foreach (string file in files)     {         File.SetAttributes(file, FileAttributes.Normal);         File.Delete(file);     }      foreach (string dir in dirs)     {         DeleteDirectory(dir);     }      Directory.Delete(targetDir, false); } 
like image 97
Brad Parks Avatar answered Oct 08 '22 01:10

Brad Parks