Why is access to the path denied?

2019-01-01 02:16发布

I am having a problem where I am trying to delete my file but I get an exception.

if (result == "Success")
{
     if (FileUpload.HasFile)
     {
         try
         {
              File.Delete(Request.PhysicalApplicationPath + app_settings.login_images + txtUploadStatus.Text);
              string filename = Path.GetFileName(btnFileUpload.FileName);
              btnFileUpload.SaveAs(Request.PhysicalApplicationPath + app_settings.login_images + filename);
         }
         catch (Exception ex)
         {
               Message(ex.ToString());
         }
      }
}

Also I should note that the folder I am trying to delete from has full control to network services.

The full exception message is:

System.UnauthorizedAccessException: Access to the path 'C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\temp_loginimages\enviromental.jpg' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path) at hybrid.User_Controls.Imgloader_Add_Edit_Tbl.btnUpdate_Click(Object sender, EventArgs e) in C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\User_Controls\Imgloader_Add_Edit_Tbl.ascx.cs:line 242

Any ideas?

23条回答
其实,你不懂
2楼-- · 2019-01-01 02:53

I had this error thrown when I tried to rename a folder very rapidly after it had been either moved or created.

A simple System.Threading.Thread.Sleep(500); solved it:

void RenameFile(string from, string to)
{
   try
   {   
      System.IO.File.Move(from, to)      
   }   
   catch 
   {  
       System.Threading.Thread.Sleep(500);      
       RenameFile(from, to);      
   }   
}
查看更多
裙下三千臣
3楼-- · 2019-01-01 02:54

An UnauthorizedAccessException exception is thrown when the operating system denies access because of an I/O error or a security error.

If you are attempting to access a file or registry key, make sure it is not read-only.

查看更多
浪荡孟婆
4楼-- · 2019-01-01 02:57

I had the exact error when deleting a file. It was a Windows Service running under a Service Account which was unable to delete a .pdf document from a Shared Folder even though it had Full Control of the folder.

What worked for me was navigating to the Security tab of the Shared Folder > Advanced > Share > Add.

I then added the service account to the administrators group, applied the changes and the service account was then able to perform all operations on all files within that folder.

查看更多
查无此人
5楼-- · 2019-01-01 03:00

This is an old issue, but I ran into it while searching. Turns out that I was missing the actual filename component in the save path for SaveAs...

string uploadPath = Server.MapPath("~/uploads");
file.SaveAs(uploadPath); // BAD
file.SaveAs(Path.Combine(uploadPath, file.FileName)); // GOOD
查看更多
只靠听说
6楼-- · 2019-01-01 03:00

Check your files properties. If the read-only is checked, uncheck it. This was my personal issue with the UnauthorizedAccessException.

查看更多
登录 后发表回答