简体   繁体   中英

Access is denied in windows forms

Iam asking this question as a series to the below link

Unable to delete .exe file through c#

While i was debugging the application,iam able to delete the .exe file.But when i try to delete the application after installing in the desktop,again iam getting the exception message as "Access is denied".

Edit:-

The code i am using to delete the file

    public bool deleteAppExecutable(string filePath)
    {
        try
        {

            if (File.Exists(filePath))
            {

                var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                di.Attributes &= ~FileAttributes.ReadOnly;
                SetAccessRule(filePath);
                File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);
                File.Delete(filePath);

            }
            return true;
        }
        catch (Exception ex)
        {
           return false;
        }
    }


    public static void SetAccessRule(string filePath)
    {

        FileInfo dInfo = new FileInfo(filePath);

        FileSecurity dSecurity = dInfo.GetAccessControl();


        dSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Delete, AccessControlType.Allow));
        dInfo.Refresh();
        dInfo.SetAccessControl(dSecurity);
    }

I found the solution why i am getting the "access is denied" exception in my application.

Since i am deleting a file inside the application through code i need to have the privilege of "Administrator".

One way is to make the user login manually as administrator.But that is not a better option.

Another way is to create an App Manifest file within your project and set the level as "administrator."

Creating App Manifest--> Right click on the project->Add new item-->Select App Manifest option from the right pane->Click ok

Open the manifest file and change the level to "requireAdministartor".

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

This will solve the issue while running the application,it will prompt user to run as administrator.

Hope this will be helpful to someone in future. :)

检查您对exe所在的文件夹(及其所有子对象)是否具有完全许可权

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM