Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 587
sebastian.roibu Avatar asked Sep 16 '25 22:09

sebastian.roibu


2 Answers

It is surprising, but not all users have access to "C:\Users\Public".

Try putting your file in Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\settings.settings";

All users should have access to write there.

Also consider using an app-specific subfolder as well.

like image 182
Steve Danner Avatar answered Sep 18 '25 12:09

Steve Danner


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.

like image 32
Gabrielle Avatar answered Sep 18 '25 11:09

Gabrielle