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?
I hit the same thing. Check to ensure that the file is NOT HIDDEN.
You need to modify the privileges of the folder you're trying to delete from/save to. Right-click on the containing folder and use the Security tab to permit modify rights for the user your application runs under.
I was facing this error because
Sometimes when I
Combine
the path with File Name andFileName = ""
It become
Path Directory
not afile
which is a problem as mentioned aboveso you must check for
FileName
like thisIn my particular case I was repeatedly creating and deleting 10000 folders. It seems to me that the problem was in that although the method
Directory.Delete(path, true)
returns, the underling OS mechanism may still be deleting the files from the disk. And when I am starting to create new folders immediately after deletion of old ones, some of them are still locked because they are not completely deleted yet. And I am getting System.UnauthorizedAccessException: "Access to the path is denied".Using
Thread.Sleep(5000)
afterDirectory.Delete(path, true)
solves that problem. I absolutely agree that this is not safe, and I am not encouraging anyone to use it. I would love to here a better approach to solve this problem to improve my answer. Now I am just giving an idea why this exception may happen.Be aware that if you are trying to reach a shared folder path from your code, you dont only need to give the proper permissions to the physicial folder thru the security tab. You also need to "share" the folder with the corresponding app pool user thru the Share Tab
According to File.Delete Method...
An
UnauthorizedAccessException
means one of 4 things: