Question

I'm new at C#, but I guess I'm using a simple command in Directory.CreateDirectory, and while I was only building in my own PC everything was fine. But when I published it and opened the app in other PC, it has thrown this exception, and I have found no answers on how to fix it on the code source. I tried to run it as admin in Win7, but didn't work also. Here's the code. It's in portuguese, but I don't think it'll be a problem :)

Thank you all so much.

string diretorio = @"C:\Program Files\LAPER\EqNumDPI\Edifícios\" + NomeEdificio;

        if (MessageBox.Show("Você tem certeza de que inseriu os dados corretamente?\nEsses campos não poderão ser alterados posteriormente.",
            "[LAPER] Cálculo do EqNumDPI", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning,
            MessageBoxDefaultButton.Button2) == DialogResult.OK)
        {
            TelaAdicionarAmbiente Tela = new TelaAdicionarAmbiente();
            if (!Directory.Exists(diretorio))
            {
                Directory.CreateDirectory(diretorio);
                StreamWriter file2 = new StreamWriter(@"C:\Program Files\LAPER\EqNumDPI\Edifícios\"+NomeEdificio+"\\metodo.txt", true, Encoding.ASCII);
                if (rBArea.Checked) file2.Write("AREA");
                else file2.Write("ATIVIDADE");
                file2.Close();
                this.Close();
            }
            else
            {
                MessageBox.Show("Nome de edifício já existe.\nPor favor, insira outro nome.",
                    "[LAPER] Cálculo do EqNumDPI",MessageBoxButtons.OK,MessageBoxIcon.Stop);
            }
        }
Was it helpful?

Solution

If it's not Oded's answer, then the issue could be the location of the exe file. If it's being run from a network volume, its permissions will be lower.

You should look into strong-name keys, using them to sign your applications, and working with your network administrator to "trust" assemblies signed by that strong name key.

Reference:

http://msdn.microsoft.com/en-us/library/h4fa028b(v=vs.80).aspx

Also - if you're on Vista or Windows 7, your app won't be able to write/create anything in the Program Files directory unless you run it as an administrator.

OTHER TIPS

This exception normally means that the account that the program runs under (by default the logged in user's account) does not have the correct permissions to create the named directory.

MSDN has this to say about UnauthorizedAccessException in the documentation for Directory.CreateDirectory:

The caller does not have the required permission.

Grant the account the correct permissions and all will be well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top