C# 对路径的访问被拒绝异常在文档中创建文件

问题描述

我正在尝试编写一个 windows 窗体应用程序,它将日志写入 .txt 文件中:

Documents/subfolder/name.txt

我可以使用

创建子文件夹目录
        string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string dirPath = Path.Combine(documentsPath,appFolderName,logFolderSubpath);

        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }

        string fileName = "log" + DateTime.Now.ToString("_yyyy-MM-dd_hh-mm-ss") + ".txt";

        string path = Path.Combine(dirPath,fileName);

但是当我尝试创建一个 StreamWriter 时:

StreamWriter writer = new StreamWriter(Path.Combine(path,filename));

其中文件名只是一个 .txt 文件名称,我得到了例外:

System.UnauthorizedAccessException
  HResult=0x80070005
  Message=Access to the path 'C:\Users\milos_qhhen\Documents\DNDice\logs\log_2021-04-30_10-30-33.txt' is denied.
  Source=mscorlib
  StackTrace:
   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,Boolean useLongPath,Boolean checkHost)
   at System.IO.FileStream..ctor(String path,Boolean checkHost)
   at System.IO.StreamWriter.CreateFile(String path,Boolean append,Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path,Encoding encoding,Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path)
   at Character_Sheet.Logger..ctor() in D:\Milos\DND\Character Sheet\Character Sheet\Logger.cs:line 35
   at Character_Sheet.MainForm.MainForm_Load(Object sender,EventArgs e) in D:\Milos\DND\Character Sheet\Character Sheet\MainForm.cs:line 57
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fignoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.Form.WmShowWindow(Message& m)
   at System.Windows.Forms.Form.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.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)

  This exception was originally thrown at this call stack:
    [External Code]
    Character_Sheet.Logger.Logger() in Logger.cs
    Character_Sheet.MainForm.MainForm_Load(object,System.EventArgs) in MainForm.cs
    [External Code]

我试图让我的应用程序将日志文件写入 Documents 目录,因为这是一个可供多人使用的程序,我想要一个可以将日志写入的固定位置。所以我需要我的程序能够创建目录,在其中创建文件,然后写入该文件!我不想在 .exe 所在的同一目录中执行此操作。

解决方法

也许您使用的用户对该文件夹没有写权限。尝试为您的用户添加写权限或简单地以管理员身份运行 VS。它应该工作