You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决C#控制台应用中的System.UnauthorizedAccessException错误

解决C#控制台程序的System.UnauthorizedAccessException错误及功能修正

我用C#编写的控制台程序运行时抛出System.UnauthorizedAccessException,同时代码逻辑存在多处错误,导致无法正确生成包含所需信息的清单文件。以下是具体的修改方案:

一、修复权限与路径问题

  • 核心问题:网络共享目录访问权限不足,或路径拼接格式错误导致文件创建失败。
  • 修改操作:
    1. 确保运行程序的账号对\\mypath\\mydirectory拥有读写权限(域环境需同时配置共享权限和NTFS权限)。
    2. 使用Path.Combine()替代字符串拼接,避免路径格式错误:
    // 原错误代码
    // string manifestDest = di + manifestFileName;
    string manifestDest = Path.Combine(di.FullName, manifestFileName);
    

二、修正资源管理错误

  • 核心问题:全局文件流重复使用导致资源释放异常,StreamWriter在循环内提前关闭导致后续写入失败。
  • 修改操作:
    1. 移除全局声明的FileStream uploadFile,改为在遍历每个文件时临时打开对应文件流。
    2. 将StreamWriter放入using语句,自动管理资源,删除循环内手动关闭/释放的代码:
    // 原错误代码
    // StreamWriter oFile = new StreamWriter(manifestDest);
    using (StreamWriter oFile = new StreamWriter(manifestDest))
    {
        oFile.WriteLine(manifestHeader);
        foreach (FileInfo finfo in files)
        {
            // 循环逻辑...
            // 移除:oFile.Close(); oFile.Dispose();
        }
    }
    

三、修正文件信息读取与哈希计算逻辑

  • 核心问题:读取行数、文件名、计算哈希的对象错误指向目录而非当前遍历的文件;哈希值未转为可读字符串。
  • 修改操作:
    1. 读取当前文件的行数:
    // 原错误代码
    // var lineCount = File.ReadAllLines(di.ToString());
    int lineCount = File.ReadAllLines(finfo.FullName).Length;
    
    1. 获取当前文件的名称:
    // 原错误代码
    // var fileName = Path.GetFileName(di.ToString());
    string fileName = finfo.Name;
    
    1. 计算当前文件的SHA256哈希并转为十六进制字符串:
    // 原错误代码
    // byte[] hashValue = mySHA256.ComputeHash(uploadFile);
    using (FileStream fileStream = finfo.OpenRead())
    {
        byte[] hashValue = mySHA256.ComputeHash(fileStream);
        string hashString = BitConverter.ToString(hashValue).Replace("-", "");
        oFile.WriteLine($"{fileName}|{feedVersion}|{lineCount}|{hashString}");
    }
    

四、优化版本判断逻辑(可选)

  • 核心问题:多条件返回相同版本号,代码冗余。
  • 修改操作:用集合判断简化逻辑:
    HashSet<string> version200Keys = new HashSet<string> { "labdata", "pharm", "claim", "hierarchy", "member*attribution" };
    HashSet<string> version220Keys = new HashSet<string> { "enrollment", "provider" };
    
    if (version200Keys.Any(key => finfo.Name.Contains(key)))
    {
        feedVersion = "200";
    }
    else if (version220Keys.Any(key => finfo.Name.Contains(key)))
    {
        feedVersion = "220";
    }
    else if (finfo.Name.Contains("member"))
    {
        feedVersion = "202";
    }
    else
    {
        feedVersion = "NA";
    }
    

完整修正后的代码

class Program
{
    static void Main(string[] args)
    {
        string path = @"\\mypath\\mydirectory";
        DirectoryInfo di = new DirectoryInfo(path);
        
        // 提前检查目录是否存在
        if (!di.Exists)
        {
            Console.WriteLine("目标目录不存在");
            return;
        }

        FileInfo[] files = di.GetFiles();
        string year = DateTime.Now.Year.ToString();
        string month = DateTime.Now.Month.ToString("d2");
        string day = DateTime.Now.Day.ToString("d2");
        string feedVersion;
        string manifestFileName = $"MyFile_{year}{month}{day}.manifest";
        string manifestDest = Path.Combine(di.FullName, manifestFileName);
        string manifestHeader = "FileName|Version|Line_Count|SHA256HASH";

        using (SHA256 mySHA256 = SHA256.Create())
        using (StreamWriter oFile = new StreamWriter(manifestDest))
        {
            oFile.WriteLine(manifestHeader);
            HashSet<string> version200Keys = new HashSet<string> { "labdata", "pharm", "claim", "hierarchy", "member*attribution" };
            HashSet<string> version220Keys = new HashSet<string> { "enrollment", "provider" };

            foreach (FileInfo finfo in files)
            {
                // 确定feedVersion
                if (version200Keys.Any(key => finfo.Name.Contains(key)))
                {
                    feedVersion = "200";
                }
                else if (version220Keys.Any(key => finfo.Name.Contains(key)))
                {
                    feedVersion = "220";
                }
                else if (finfo.Name.Contains("member"))
                {
                    feedVersion = "202";
                }
                else
                {
                    feedVersion = "NA";
                }

                try
                {
                    // 获取文件行数
                    int lineCount = File.ReadAllLines(finfo.FullName).Length;
                    string fileName = finfo.Name;

                    // 计算文件SHA256哈希
                    string hashString;
                    using (FileStream fileStream = finfo.OpenRead())
                    {
                        byte[] hashValue = mySHA256.ComputeHash(fileStream);
                        hashString = BitConverter.ToString(hashValue).Replace("-", "");
                    }

                    // 写入清单文件
                    oFile.WriteLine($"{fileName}|{feedVersion}|{lineCount}|{hashString}");
                }
                catch (UnauthorizedAccessException ex)
                {
                    Console.WriteLine($"无权限访问文件 {finfo.Name}: {ex.Message}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"处理文件 {finfo.Name} 出错: {ex.Message}");
                }
            }
        }

        Console.WriteLine("Success");
    }

    public static void PrintByteArray(byte[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write($"{array[i]:X2}");
            if ((i % 4) == 3) Console.Write(" ");
        }
        Console.WriteLine();
    }
}

内容的提问来源于stack exchange,提问作者SidC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 20:03:16