首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#和File.WriteAllText错误

C#和File.WriteAllText错误
EN

Stack Overflow用户
提问于 2012-03-02 21:07:25
回答 4查看 13.4K关注 0票数 3

我正在构建一个简单的C#应用程序,它必须将用户输入写到一个文件中。

我的第一个问题是,我希望用户能够设置设置文件的路径,但我希望程序能够在以下启动时读取设置文件。

我的第二个问题是,如果我使用像这样的东西:

代码语言:javascript
复制
    File.WriteAllText(@"C:\Users\Public\settings.settings", message);

我得到以下错误:

代码语言:javascript
复制
    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

有什么想法吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-03-02 22:12:53

右键单击项目的=>属性并检查Security选项卡。取消选中“启用ClickOnce安全设置”,然后重试。如果问题仍然存在,请取消选中Signing选项卡中的only选项。

票数 3
EN

Stack Overflow用户

发布于 2012-03-02 21:12:31

这很令人惊讶,但并不是所有的用户都可以访问"C:\Users\Public"

尝试将您的文件放入Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\settings.settings";

所有用户都应该有权在那里写入。

另外,也可以考虑使用特定于应用程序的子文件夹。

票数 5
EN

Stack Overflow用户

发布于 2015-03-28 04:58:09

我必须以管理员身份运行我的应用程序,才能写入c:中受保护的文件夹。例如,如果在visual studio中调试您的应用程序,请确保右键单击"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe“并选择”以管理员身份运行“。然后从那里打开你的解决方案。我的应用程序试图写入c:\的根目录

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9533820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档