Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:UsersKristjanBEsturDocumentsmessage.txt",
        FileMode.Append, FileAccess.Write);
        sw = new StreamWriter(fs);
        sw.WriteLine(s);
        sw.Flush();
        sw.Close();
        fs.Close();
        File.Delete(@"C:UsersKristjanBEsturDocumentsmessage.txt");
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
826 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...