在c#中使用TextWriter写入文件时取消AuthorAccessException

时间:2012-11-25 05:42:29

标签: c# .net

我有一个错误说“访问路径'C:\ Program Files(x86)\ My Program \ bin \ Debug \ myName.data'被拒绝”

这是我的代码

TextWriter tw = new StreamWriter("bin\\Debug\\myName.data");

tw.Write(txtLoginName.Text);
tw.Close();

我已经为我的所有项目文件提供了完全的Controll权限。我制作安装程序,以便客户端将它安装在他们的电脑中,当检查文件时,我发现没有给用户提供写访问权限。如何处理这个

=============

************** Exception Text **************
System.UnauthorizedAccessException: Access to the path 'C:\Program Files (x86)\My Program\bin\Debug\myName.data' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   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)
   at System.IO.StreamWriter.CreateFile(String path, Boolean append)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.StreamWriter..ctor(String path)
   at clientChat.Form2.button1_Click(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

2 个答案:

答案 0 :(得分:1)

安装程序将在用户的登录上下文中运行,并且系统的普通用户无权写入Program Files或其他此类系统文件夹。

您需要将文件夹的位置移动到用户的App数据文件夹。或安装程序创建的其他一些常用位置。

答案 1 :(得分:0)

普通用户无法通过设计将程序文件(以及系统文件夹中的其他位置)写入。

请使用文档文件夹或其他每个用户的位置来存储用户的数据。 Environment.GetFolderPath可让您为当前用户获取正确的位置,请考虑Environment.SpecialFolder适用于您的案例,并将其用作基本文件夹。

Followng示例将在“我的文档”文件夹中提供路径:

var pathToFile = Path.Combine(
  Environment.GetFolderPath(Environment.SpecialFolder.Personal),
  "my_file_name.txt");
相关问题