Search code examples
c#file-permissions

C# and File.WriteAllText error


I am building a simple C# application that has to write the user input in a file.

My first problem is that i want the user to be able to set the path of the settings file, but i want the program to be able to read the settings file on the following starts.

My second problem is that if i use something like :

    File.WriteAllText(@"C:\Users\Public\settings.settings", message);

i get the following error :

    System.Security.SecurityException: Request for the permission of type 
    'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, 
    Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at 
    System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& 
    stackMark, Boolean isPermSet)   at System.Security.CodeAccessPermission.Demand()
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, 
    Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions 
    options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, 
    FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)

    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, 
    FileShare share, Int32 bufferSize, FileOptions options)

     at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
    at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
    at System.IO.File.WriteAllText(String path, String contents, Encoding encoding)
    at IMDBGrabber.frmSettings.writeToFile(String p)
    The action that failed was: Demand

    The type of the first permission that failed was: System.Security.Permissions.FileIOPermission

    The Zone of the assembly that failed was: MyComputer

Any ideas ?


Solution

  • Right click on the project => properties and check the Security tab. Uncheck "Enable ClickOnce security settings" and try again. If the problem persists uncheck the only option from Signing tab as well.