System.UnauthorizedAccessException was unhandled

somethingSomething picture somethingSomething · Dec 7, 2013 · Viewed 37.2k times · Source

I am getting a access denied exception. How can I fix this?

Here is the exception:

System.UnauthorizedAccessException was unhandled HResult=-2147024891 Message=Access to the path 'c:\message.txt' is denied.
Source=mscorlib

Here is the code:

    public static void WriteToFile(string s)
    {
        fs = new FileStream("c:\\message.txt",
        FileMode.Append, FileAccess.Write);
        sw = new StreamWriter(fs);
        sw.WriteLine(s);
        sw.Flush();
        sw.Close();
        fs.Close();
    }

EDIT: It works if I run vs2012 as administrator, but is there a way or a reason to do it as normal user?

And this works:

    public static void WriteToFile(string s)
    {
        fs = new FileStream(@"C:\Users\KristjanBEstur\Documents\message.txt",
        FileMode.Append, FileAccess.Write);
        sw = new StreamWriter(fs);
        sw.WriteLine(s);
        sw.Flush();
        sw.Close();
        fs.Close();
        File.Delete(@"C:\Users\KristjanBEstur\Documents\message.txt");
    }

Answer

Ahmed Syed picture Ahmed Syed · Jan 30, 2014

Double click on app.manifest file and if app.manifest not present Right click on your project, add -> New Item -> Application Manifest File then replace this line

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

with this

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

It will run your application with administrator privileges.