简体   繁体   English

尝试在C#中写入文本文件时出现UnauthorizedAccessException

[英]UnauthorizedAccessException when trying to write to text file in C#

I'm trying to write a blank text file which is included within my installer but i'm getting the following error; 我正在尝试编写一个空白文本文件,该文件包含在安装程序中,但出现以下错误;

System.UnauthorizedAccessException: Access to the path 'C:\Program Files (x86)\Hex Technologies\wamplocation.txt' is denied.

It seems to be the permissions of the file once it's installed through my installer, but how can I set the file to be fully modifiable once the file installed?! 通过安装程序安装后,似乎是文件的权限,但是一旦安装文件,如何将文件设置为可完全修改? Can this be done through C#?! 可以通过C#完成吗?

EDITTED; 编辑;

           wamp_url = openFileDialog1.FileName.ToString();
           String EnviromentPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
           StreamWriter outfile = new StreamWriter(EnviromentPath + @"\Hex Technologies\wamplocation.txt");
           outfile.Write(wamp_url);
           outfile.Close();

You should not store your modifyable data files in the Program Files path. 您不应将可修改的数据文件存储在“程序文件”路径中。 Use Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) or Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) 使用Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)

The Program Files\\... path is protected against modification by normal users on Win7+. 程序文件\\ ...路径受到保护,不会受到普通用户在Win7 +上的修改。 It would be a bad idea to try to circumvent that protection. 试图避开这种保护是一个坏主意。

The likleyhood is the UAC is getting in your way. 最有可能的是UAC妨碍了您的前进。

Ideally your program shouldn't be writing to this location, it this modification file is to be modified during an install process and nowhere else you need to make sure that you are running elevated. 理想情况下,您的程序不应该写入此位置,而要在安装过程中修改此修改文件,并且无需确保安装在提升位置。

If this file is to be modified at run time you should consider the use of either %appdata% for user data or %programdata% for program data instead of program files. 如果要在运行时修改此文件,则应考虑将%appdata%用于用户数据,或者将%programdata%用于程序数据而不是程序文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM