213

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?

durron597
  • 31,968
  • 17
  • 99
  • 158
nick gowdy
  • 6,191
  • 25
  • 88
  • 157
  • 5
    What isn't clear about the exception? The account that the application is running under does not have access privileges to the file/folder. – Oded Jan 11 '12 at 15:01
  • 9
    I understand what the exception is saying. The problem is this functionality is used by a some users who need to modify images using the system. Part of that is replacing images by deleting the old image and saving a new image. – nick gowdy Jan 11 '12 at 15:25
  • Check your access permissions to the folder. give the proper permissions to the folder using security tab from properties window – gasroot May 23 '13 at 17:01
  • 14
    The exception is not informative at all. It doesn't tell you: A. What principal is trying to access the resource B. What permission does it need. To find out, it requires installing Windows SysInternals and monitoring the path access. – ATL_DEV Nov 02 '17 at 14:30
  • You shouldn't be deleting files from the Visual Studio project folder in your application. If this is a temporary file, save it to and delete it from the [temporary folder](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath). – Corvus Jul 12 '23 at 01:17

32 Answers32

286

According to File.Delete Method...

An UnauthorizedAccessException means one of 4 things:

  • The caller does not have the required permission.
  • The file is an executable file that is in use.
  • Path is a directory.
  • Path specified a read-only file.
CrazyTim
  • 6,695
  • 6
  • 34
  • 55
  • 4
    I checked the file and rights, everything seemed fine. I checked the user. I could delete the file manually via Explorer. It turns out that it was a read only file. I am not sure why that should matter on the delete, as it was not in use. Anyway, all I did was add some code: if (myFile.Attributes.HasFlag(FileAttributes.ReadOnly)) { myFile.Attributes-= FileAttributes.ReadOnly; } myFile.Delete(); – Outside the Box Developer Mar 26 '18 at 19:31
  • or simply: myFile.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly; – Outside the Box Developer Mar 26 '18 at 19:36
  • Echoing Outside the Box Developer, I found that my own instance was a combination of the file being a read-only file, and use of the @ symbol with a path that already had the necessary escape characters. – baker.nole Dec 24 '20 at 20:42
  • Had this using `System.IO.FileStream.Init` and the file was read-only. Then why don't just read it? Removed read-only flag from the file and the exception was gone. Brilliant! – Andreas Mar 11 '21 at 10:46
  • 1
    What does "Path is a directory" mean? – Tris Jun 01 '21 at 01:56
  • 2
    @Tris, it means that the path leads to a directory, not a file. – Lukas Jun 03 '21 at 16:45
  • 1
    This is misleading, the exceptions should at least specify the reason either in the message, or better through a member. – Valentino Miori Jul 30 '21 at 12:46
  • I get this intermittently and not sure why. The only thing that might be related is that a file I am trying to rename (move) is extensionless and the could perhaps be interpreted as a directory? – ProNotion Oct 06 '22 at 12:31
195

I also had the problem, hence me stumbling on this post. I added the following line of code before and after a Copy / Delete.

Delete

File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);

Copy

File.Copy(file, dest, true);
File.SetAttributes(dest, FileAttributes.Normal);
Riaan
  • 3,423
  • 4
  • 30
  • 36
  • 19
    I gave 'Everyone' full permissions to the folder without success. Somehow these file attributes worked though. Thanks. I wish MS would finally settle on a proper security model. Trying to figure out why Copy/Delete explodes every few years is frustrating to say the least. – Steve Jan 07 '13 at 21:43
  • 14
    SetAttributes Normal was the trick for me - I was trying to File.Copy and overwrite a read-only file.. – Tom Hunter Feb 28 '13 at 16:51
  • 6
    Access to the path is denied doesn't suggest that the file is simply readonly (since you do actually have access to the path!) In my opinion the error message should be changed. Thanks for the hint anyways! – MBoros Feb 19 '14 at 13:57
  • 1
    I ran the program as Administrator and the issue was gone. – Santiago Villafuerte Oct 15 '15 at 21:22
  • 1
    Was running as admin and admin had full control over the directory and it still wouldn't save. This issue appeared to just crop up. That is, I was able to save and then all of a sudden it stopped working. Your answer worked though. I hope it's safe for TFS source control.... –  Jun 19 '16 at 19:40
  • ^ FileAttributes.Archive makes it match the behavior of TFS for me –  Jun 19 '16 at 19:56
  • 5
    How does setting an attribute after a copy operation helps? Won't the program crash already on copy statement? Should it be before copy operation just like delete operation? –  Nov 02 '17 at 08:16
  • @VibhoreTanwer, the copy of the file creates a new file as it doesn't use the first file. Setting the attributes makes sure you can work with the file afterwards as it might be read-only or hidden. In order to delete the file it needs to be Normal attribute and if you want to do something with the copied file it has to be normal as well. By process of elimination we figured it out as it makes logical sense. – Riaan Apr 23 '18 at 09:06
  • 1
    Old post, but thanks. I had the same trouble deleting temporary files that I copied to a folder where the user had full permissions. Setting each file's attributes to normal before deleting it stopped the UnauthorizedAccess exception from occurring. – netcat Jun 15 '18 at 18:46
  • How does one run the program as Administrator? – Tris Jun 01 '21 at 01:54
  • For me it was over zealous Norton AV blocking the write – azpc Aug 18 '21 at 15:29
  • 1
    This worked for me as well, but can anyone explain why it works? – Per Jan 13 '23 at 17:22
37

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
vakio
  • 3,134
  • 1
  • 22
  • 46
Andrew Edvalson
  • 7,658
  • 5
  • 26
  • 24
24

When a user tries to connect to your Web site, IIS assigns the connection to the IUSER_ComputerName account, where ComputerName is the name of the server on which IIS is running. By default, the IUSER_ComputerName account is a member of the Guests group. This group has security restrictions. Try to grand access to IUSER_ComputerName to that folder

Here is very good described answer about IIS security

Hope this helps

Community
  • 1
  • 1
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
22

I got the error because I didn't realize that the destination should be a file. I had a folder as the second parameter (which works in cmd). and I got Unhandled Exception: System.UnauthorizedAccessException: Access to the path is denied. because C# File.Move wants a file there, not just for the first parameter, but for the second too, and so if you put a directory as second parameter, it's trying to write a file like c:\crp when you have a directory called c:\crp.

this would be incorrect File.Move(args[0],"c:\\crp");

So, this would be correct File.Move(args[0],"c:\\crp\\a.a");

The same goes for File.Copy

OrionMD
  • 389
  • 1
  • 7
  • 13
barlop
  • 12,887
  • 8
  • 80
  • 109
  • 1
    Thank you! This indirectly solved an issue where an API was expecting a destination which I gave as the directory, not realizing it had to include the filename (since the object itself has an associated filename). – Austin Salgat Oct 05 '17 at 18:29
19

Right-click on Visual studio and click Run as Administrator

Thanks for +1

Alexander Zaldostanov
  • 2,907
  • 4
  • 30
  • 39
  • 1
    This was the solution for my File.Move issue on a Windows 8.1 Enterprise machine on which I was local administrator, and nothing else had a handle on the files. – Robert Kerr May 16 '16 at 21:25
11

If this is an IIS website that is having the problem, check the Identity property of the advanced settings for the application pool that the site or application uses. You may find that it is set to ApplicationPoolIdentity, and in that case then this is the user that will have to have access to the path.

Or you can go old style and simply set the Identity to Network Service, and give the Network Service user access to the path.

Bjørn Otto Vasbotten
  • 1,673
  • 1
  • 23
  • 32
7

same issue for me too, I was pointing the folder instead of file.

so make sure in path, give path+filename

System.IO.File.WriteAllBytes("path", bytearray);
pushkin
  • 9,575
  • 15
  • 51
  • 95
jineesh vp
  • 71
  • 1
  • 3
6

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.

reza.Nikmaram
  • 179
  • 2
  • 4
6

I have also faced this issue when my window service started throwing the exception

System.UnauthorizedAccessException: Access to the path "C:\\Order\\Media
44aa4857-3bac-4a18-a307-820450361662.mp4" is denied.

So as a solution, I checked the user account associated with my service, as shown in below screen capture

enter image description here

So in my case it was NETWORK SERVICE

And then went to the folder properties to check if the associated user account also exists under their permission tab. It was missing in my case and when I added it and it fixed my issue.

For more information please check the below screen capture

enter image description here

Jitender Kumar
  • 2,439
  • 4
  • 29
  • 43
6

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.

Brissles
  • 3,833
  • 23
  • 31
  • you are assuming that he is admin of his machine.. if this is a work machine and he's just a user .. they probably set the permissions up that way for a reason.. since we are only left to assume – MethodMan Jan 11 '12 at 15:06
  • 1
    It is a work machine and I am a power user. I don't log in as administrator. The properties of the image folder have been modified so network services has full access. But that didn't make any difference. – nick gowdy Jan 11 '12 at 15:24
  • 1
    I just added "Everyone" with full access to the folder, and "voilá" – MarceloBarbosa Jan 17 '17 at 13:45
5

The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

I hit the same thing. Check to ensure that the file is NOT HIDDEN.

Ghasem
  • 14,455
  • 21
  • 138
  • 171
Ron H
  • 75
  • 1
  • 5
  • Got Access Denied error when `FileStream(path, FileMode.Create)` was used and if file already existed and the file was hidden. – sameerkn Apr 07 '21 at 06:37
4

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

4

I got this error and solved it in just a moment. Don't know why all of my folders are read-only,I cancelled the read-only and apply it. However, it is still read-only. So I moved the file into the root folder, it works - so weird.

TomServo
  • 7,248
  • 5
  • 30
  • 47
MOLLMY
  • 41
  • 2
  • I cancelled the read-only, applied it, and it worked. As you say, the folder still shows as read-only afterwards for me too, but it solved it for me without need for further action. – thesystem Jul 15 '21 at 08:54
4

I was facing this error because

Sometimes when I Combine the path with File Name and FileName = ""

It become Path Directory not a file which is a problem as mentioned above

so you must check for FileName like this

if(itemUri!="")
        File.Delete(Path.Combine(RemoteDirectoryPath, itemUri));
Community
  • 1
  • 1
Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
4

I was trying to use System.IO.File.OpenWrite(path)

and it did not work because I was only passing OpenWrite() a path to a directory, but it requires a path all the way to the file you want to write. So a full path including the filename.extension at the end needs to be passed into OpenWrite to avoid UnauthorizedAccessException

SeanMC
  • 1,960
  • 1
  • 22
  • 33
4

In my case the problem was Norton. My in-house program doesn't have the proper digital signature and when it tried to delete a file it gave the UnauthorizedAccessException.

enter image description here

If it give you a notification, you can handle it from there. In my case it didn't give a notification that I noticed. So here's how to keep Norton from blocking the program.

  1. Open Norton
  2. Click the down arrow
  3. Click History
  4. Find activity by program
  5. Click More Options
  6. Click Exclude Process
D_Bester
  • 5,723
  • 5
  • 35
  • 77
3

To solve this problem, I follow the Scot Hanselman approach at Debugging System.UnauthorizedAccessException (often followed by: Access to the path is denied) article, the code with example is bellow:

class Program
{
    static void Main(string[] args)
    {
        var path = "c:\\temp\\notfound.txt";
        try
        {
            File.Delete(path);
        }
        catch (UnauthorizedAccessException)
        {
            FileAttributes attributes = File.GetAttributes(path);
            if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                attributes &= ~FileAttributes.ReadOnly;
                File.SetAttributes(path, attributes);
                File.Delete(path);
            }
            else
            {
                throw;
            }
        }
    }
}
Antonio Leonardo
  • 1,805
  • 1
  • 8
  • 18
2

I had the same problem on a newly moved website on a shared server. Solved through the web host panel (DotNetPanel) setting true the "allow write permissions". So if you are in a shared server before reviewing all code worth taking a look at the server configuration and could save you a lot of time.

Drakell
  • 150
  • 1
  • 10
2

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

Kacho
  • 21
  • 1
2

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.

LuTheZy
  • 61
  • 8
2

For those trying to make a UWP (Universal Windows) application, file permissions are much more restricted, and in general is deny by default. It also supersedes the system user permissions. You will basically only have access to files in either

  • Your install location
  • Your AppData location
  • Files selected through the File or Folder picker
  • Locations requested in your App Manifest

You can read more here for details => https://learn.microsoft.com/en-us/windows/uwp/files/file-access-permissions

Tezra
  • 8,463
  • 3
  • 31
  • 68
2

If you're using BitDefender there's a good chance its Safe Files feature blocked your operation. This is a form of Ransomware protection that comes with some of its more advanced versions.

Make sure to grant your application access in BitDefender and try again.

Some more details can be found in this BitDefender support page.

Vlad Schnakovszki
  • 8,434
  • 6
  • 80
  • 114
2

In my case it was my AVG anti-virus that triggered the exception.

I added my VS Projects directory to the "Allowed" list. And I had to add the executable to the AVG exceptions list after I copied the .exe to my App directory.

benhorgen
  • 1,928
  • 1
  • 33
  • 38
  • Thanks for pointing me in this direction - this was the issue for me too! Specifically, the AVG Ransomware Protection was the culprit. – Craig Brown Sep 16 '21 at 13:53
2

I've had the same problem and I've managed to get it working by changing the partition on which the file will be saved. So, on line 5 I've changed @"C:\" to be @"D:\" and that resolved the problem.

static void SaveVideoToDisk(string link)
{
    var youTube = YouTube.Default; // starting point for YouTube actions
    var video = youTube.GetVideo(link); // gets a Video object with info about the video
    File.WriteAllBytes(@"D:\" + video.FullName, video.GetBytes());
}
2

After migrating from Visual Studio 2017 to Visual Studio 2019 I faced two exceptions with two of my applications which run properly under Visual Studio 2017:

  • System.UnauthorizedAccessException
  • System.ArgumentException

It turned out that I had to add the executables of the two applications to the allowed apps of Avast Antivirus.

Pollitzer
  • 1,580
  • 3
  • 18
  • 28
  • Solved my issue, thought I was going mad as I could save the file to the DIR but I couldn't overwrite it after restarting the program. Do you know if there is an alternative solution to adding an exception? – MCC Mar 17 '22 at 21:11
  • @MCC: Sorry, no, I stopped working on the issue. – Pollitzer Mar 18 '22 at 10:44
1

In 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".

enter image description here

Using Thread.Sleep(5000) after Directory.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.

class Program
{
    private static int numFolders = 10000;
    private static string rootDirectory = "C:\\1";

    static void Main(string[] args)
    {
        if (Directory.Exists(rootDirectory))
        {
            Directory.Delete(rootDirectory, true);
            Thread.Sleep(5000);
        }

        Stopwatch sw = Stopwatch.StartNew();
        CreateFolder();
        long time = sw.ElapsedMilliseconds;

        Console.WriteLine(time);
        Console.ReadLine();
    }

    private static void CreateFolder()
    {
        var one = Directory.CreateDirectory(rootDirectory);

        for (int i = 1; i <= numFolders; i++)
        {
            one.CreateSubdirectory(i.ToString());
        }
    }
}
OrionMD
  • 389
  • 1
  • 7
  • 13
Aleksei Mialkin
  • 2,257
  • 1
  • 28
  • 26
1

First just check the path if the colon(:) character is missing or not after the drive letter. If colon is not missing then you can check if access/write permission is granted for that path. I had the same issue and i was only missing the colon, permission and everything else was fine.

C:\folderpath

will work fine but,

C\folderpath .........(missing colon)

will give you access denial error.

OrionMD
  • 389
  • 1
  • 7
  • 13
Vijay Dodamani
  • 264
  • 1
  • 9
1

I also ran into this post as dealing with the same issue. Looks like the file is in use and hence not able to write to it. Though not able to figure it out, which process is using it. Signed out the other user who was logged in in that box, dont see any users who is holding it. Any quick tips regarding on how to find the same.

Thanks, Lakshay (developer)

  • In your answer don't post a new question, but try to answer the question of the original poster with helpful information. For your own question please search stackoverflow first for the same or similar questions. If you don't find any, post a new question following this guide: [How to ask a good question](https://stackoverflow.com/help/how-to-ask) – Aleksandar Sep 14 '19 at 02:09
1

I too faced the same problem when trying to do this after deployment at server:

dirPath = Server.MapPath(".") + "\\website\\" + strUserName;
if (!Directory.Exists(dirPath))
{
    DirectoryInfo DI = Directory.CreateDirectory(dirPath);
}
string filePath = Server.MapPath(".") + "\\Website\\default.aspx";
File.Copy(filePath, dirPath + "\\default.aspx", true);
File.SetAttributes(dirPath + "\\default.aspx", FileAttributes.Normal);

I granted permission in IIS to other group including administrator and my problem got solved.

eeerahul
  • 1,629
  • 4
  • 27
  • 38
0

I have found that this error can occur in DESIGN MODE as opposed to ? execution mode... If you are doing something such as creating a class member which requires access to an .INI or .HTM file (configuration file, help file) you might want to NOT initialize the item in the declaration, but initialize it later in FORM_Load() etc... When you DO initialize... Use a guard IF statement:

    /// <summary>FORM: BasicApp - Load</summary>
    private void BasicApp_Load(object sender, EventArgs e)
    {
        // Setup Main Form Caption with App Name and Config Control Info
        if (!DesignMode)
        {
            m_Globals = new Globals();
            Text = TGG.GetApplicationConfigInfo();
        }
    }

This will keep the MSVS Designer from trying to create an INI or HTM file when you are in design mode.

Terry
  • 1
0

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);      
   }   
}
ThP
  • 2,312
  • 4
  • 19
  • 25
  • Think it would be better if you checked if the folder existed before moving it rather than sleeping for half a second... if the OS is busy the previous move might take longer than half a second, and your back to the same issue. – Paul Zahra Jun 10 '16 at 13:28
  • This piece of code is very dangerous. It repeats the RenameFile method no matter what exception is thrown! It could cause the app to crash if the cause of exception is an actual permission problem – Hossein Shahdoost Jun 19 '16 at 05:42