【问题标题】:Creating a TXT file and saving it onto DISK C: using system.io , but access is denied创建 TXT 文件并将其保存到 DISK C: 使用 system.io ,但访问被拒绝
【发布时间】:2020-04-27 19:51:26
【问题描述】:

我正在尝试使用 system.io 创建一个 TXT 文件,我输入了文件路径,但每次我运行它时,我的访问都被拒绝,对每个文件夹 i C: ,在 DISK D: 一切都很好,是有一个解决方案,我的意思是,我可以在代码中以某种方式访问​​它吗?

我使用的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;

namespace KeyLoggerA1
{
    class Program
    {
        private static int WH_KEYBOARD_LL = 13; //hook procedure type , monitoring low-level keyboard input events
        private static int WM_KEYDOWN = 0x0100;
        private static IntPtr hook = IntPtr.Zero;
        private static LowLevelKeyboardProc llkProcedure = HookCallback;



        static void Main(string[] args)
        {
            string filePath = @"C:\Program Files\Test.txt";

            if (!File.Exists(filePath))
            {
                using (StreamWriter sw = File.CreateText(filePath))
                {
                    sw.WriteLine("test");
                }
            }

我得到的错误:

未处理的异常:System.UnauthorizedAccessException:对路径“C:\Program Files\Test.txt”的访问被拒绝。 ... 在 System.IO.File.CreateText(字符串路径) 在 C:\Users\mirer\source\repos\ConsoleApp2\ConsoleApp2\Program.cs:第 28 行中的 KeyLoggerA1.Program.Main(String[] args) 处

如果有人可以提供帮助,将不胜感激

【问题讨论】:

  • 报错信息有什么不清楚的地方?您无权写入“程序文件”。例如,试试你的主目录。
  • ProgramFiles 和系统驱动器上的许多其他特殊文件夹需要提升/管理员访问权限。尝试写入用户的 AppData 以验证是否是这种情况。

标签: c# system.io.file


【解决方案1】:

确保使用System.IO.Path.Combine(),因为它是连接文件路径的正确方法。

现在问你的问题,这很正常。您只需提升程序(以管理员身份运行)即可访问该文件夹。 如果您想检查程序当前是否以管理员身份运行,check this outand this

【讨论】:

  • Path.Join 和什么有什么关系?如果您不希望在Path.Combine 中内置额外的生根逻辑,那么它只是“正确的”,并且它仅在 dotnet core 2.1+ 和 netstandard 2.1 中可用。 OP 没有说明他们正在编译什么(完整框架、dotnet 核心等),所以看起来就像随机不相关的建议。
  • 我其实是想说Path.Combine,我的错。
【解决方案2】:

该程序没有适当的权限来写入您的目的地。尝试以管理员身份运行程序或保存到其他位置(我知道您正在尝试保存到程序文件,因此您可能无法保存到其他位置)

【讨论】:

    【解决方案3】:

    我认为如果你在 c 中有一个文件夹来存放你的文本文件,你可以将其设置为身份验证设置兄弟

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2023-03-08
      相关资源
      最近更新 更多