System.Unauthorizedaccessexception in C#

Asked

Viewed 5,247 times

2

Well, I’m trying to develop an automatic setup for a program I developed. First, it would create a folder in C:/Filename; then it would download a Github repository as .zip in this folder, then export the zip to it and finally remove .zip. Missing add something to run setup, but the problem is not there.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace C_Sharp_WIndowsFormTest
{
    class setup
    {
public static void download(string url, string path, string githubToken)
    {

        using (var client = new System.Net.Http.HttpClient())
        {
            var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", githubToken);
            credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(credentials));
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
            var contents = client.GetByteArrayAsync(url).Result;
            System.IO.File.WriteAllBytes(path, contents);
        }

    }

    public static void JustDoIt()
    {

        string directory = "C:/NomeDaPasta";
        string githubToken = "MeuGithubToken";
        string url = "UrlDoRepositório";

        if (!Directory.Exists(directory))
        {

            /*## Cria a Pasta##*/

            Directory.CreateDirectory(directory);
            download(url, directory, githubToken);
            ZipFile.ExtractToDirectory("C:/NomeDaPasta/Repositório.zip", directory);

            /*## Deleta o zip ##*/
            File.SetAttributes(directory, FileAttributes.Normal);
            File.Delete("C:/NomeDaPasta/Repositório.zip");

            /*## Final (Deleta a pasta) ##*/
            Directory.Delete(directory);


        }
        else
        {

            MessageBox.Show("Folder already exists!");
            Directory.Delete(directory);
            JustDoIt();

        }

    }

    static void Main(string[] args)
    {

        try
        {

            JustDoIt();             

        } catch (Exception e)
        {

            MessageBox.Show(e.ToString());

        }

    }

}

}

NOTE: I just copied the code from Download someone else.

This is the code, but when executing it, it returns me the following error:

System.UnauthorizedAccessException: O acesso ao caminho 'C:/NomeDaPasta' foi negado.

I’ve looked for help, but I didn’t succeed. Please, someone help me!

  • 1

    Have you ever tried to do the process in another directory without being at the root of C://Drive? Type try to do in another folder outside of C:/Filename, as you are doing.

  • 1

    Have you tried to give permission in the folder?

  • @Wesleyheron would even do but how the path would be set, since it can vary from pc to pc? If you have any way please tell me!

  • @jbueno followed a tutorial to add permission to the program using visual studio( the IDE I use ) apparently should work but not.

  • 1

    Why not add permission using Windows itself? Right-click on the folder > Estates > Security, etc..

  • but that wouldn’t apply to every computer, everyone who wanted to download my program would have to do this, and I don’t want that.

  • See if it helps https://msdn.microsoft.com/en-us/library/system.io.directory.setaccesscontrol(v=vs.110). aspx

Show 2 more comments

3 answers

2

You can run your application as an administrator. In fact, Voce can indicate that the application should be executed only with administrator rights. For this, Voce has to create a manifesto for its application .

inserir a descrição da imagem aqui

And you have to change permissions to administrator

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

Source

To avoid executing your application as an administrator write elsewhere such as

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
  • 1

    Since it is an installer I believe that it is not a problem to execute as an administrator

1

Replace these points:

string directory = @"C:\\NomeDaPasta";

string caminhoZip = @"C:\\NomeDaPasta\\Repositório.zip";

ZipFile.ExtractToDirectory(caminhoZip, directory);

File.Delete(caminhoZip);

0

You need to edit folder security options, because the process that is calling folder creation and deletion functions does not have the Read and/or write credentials to perform such an operation.

You can confirm this by changing the path to a generic to take the test:

string directory = @"C:\\Users\\Public\\Teste";

With this path (which by the way is more accessible), you will be able to generate what you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.