1

I'm trying to write an xml file and attach it to an email. It works great if I give it a path to my personal documents folder(i.e. C:\users\myname\Documents\Test.xml), but if I try to change it to something like C:\\Test.xml, I get the following error message:

UnauthorizedAccessException was Unhandled Access to the path 'C:\Test.xml' is denied.

(I can't post pictures apparently)

What would be a good workaround for this?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

3 Answers3

1

To get the directory in which the application is launched you could use AppDomain.CurrentDomain.BaseDirectory

On Admin privileges:

  1. Check if the user has launched the application using Run as Administrator. In this case user should have admin privileges to write..Here is sample code..

        var identity = WindowsIdentity.GetCurrent();
        var principal = new WindowsPrincipal(identity);
        if (principal.IsInRole(WindowsBuiltInRole.Administrator))
        {
            //Application is Running as ADMIN
        }
    
  2. You could always write it to you TEMP or LOCAL APP DATA folder..

        var temp = Path.GetTempPath();
    
        //e.g: C:\Users\UserName\AppData\Local\Temp\test.xml
        var testFilePath = Path.Combine(temp, "test.xml");
    
jacob aloysious
  • 2,547
  • 15
  • 16
0

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly(‌​).CodeBase)

see How can I get the application's path in a .NET console application?

Community
  • 1
  • 1
Bruce Burge
  • 144
  • 1
  • 15
0

Program folder is not always allowed to write, use %TEMP% folder instead.

Pavlus
  • 1,651
  • 1
  • 13
  • 24