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

已用try-catch仍出现access denied导致程序终止的问题求助

问题解决办法

你的代码失效主要有两个核心原因:一是多次调用File.ReadLines重复打开文件,增加了被其他进程占用的概率,第二次打开时触发的异常会打断流程;二是捕获异常后循环变量printerlinecount未递增,导致程序卡在原地反复尝试读取同一位置,甚至陷入无限循环。

优化方案1:一次性读取文件所有行(推荐)

把文件内容一次性读取到内存列表中,仅打开一次文件,彻底避免多次打开导致的冲突问题:

List<string> fileLines = null;
try
{
    // 一次性读取所有行到内存,仅打开一次文件
    fileLines = File.ReadLines(printerinfofile).ToList();
}
catch (IOException)
{
    if (Settings.loglevel > 1)
    {
        Console.WriteLine("文件被其他应用占用,无法读取");
    }
    // 读取失败直接退出循环
    break;
}

while (printerlinecount < Gvalue.LineCount && printerlinecount < fileLines.Count)
{
    try
    {
        string parameter = fileLines[printerlinecount];
        string parameterc = parameter.Trim(new[] { '[', ']' });
        string printervalue = fileLines[printerlinecount + 2];
        string printervaluec = printervalue.Substring(6);
        
        printerstatusvalues.Add(parameterc, printervaluec);
        printerlinecount += 4;
    }
    catch (ArgumentOutOfRangeException)
    {
        if (Settings.loglevel > 1)
        {
            Console.WriteLine("文件行数不足,终止读取");
        }
        break;
    }
}

优化方案2:单循环内仅打开一次文件(适合大文件)

如果文件过大无法一次性加载到内存,可在每次循环中用StreamReader手动控制读取流程,确保单循环内只打开一次文件:

while (printerlinecount < Gvalue.LineCount)
{
    try
    {
        using (var reader = new StreamReader(printerinfofile))
        {
            // 跳过指定行数
            for (int i = 0; i < printerlinecount; i++)
            {
                if (reader.EndOfStream) throw new ArgumentOutOfRangeException();
                reader.ReadLine();
            }

            // 读取目标行
            string parameter = reader.ReadLine() ?? throw new ArgumentOutOfRangeException();
            string parameterc = parameter.Trim(new[] { '[', ']' });

            // 跳过中间一行
            if (reader.EndOfStream) throw new ArgumentOutOfRangeException();
            reader.ReadLine();

            string printervalue = reader.ReadLine() ?? throw new ArgumentOutOfRangeException();
            string printervaluec = printervalue.Substring(6);

            printerstatusvalues.Add(parameterc, printervaluec);
            printerlinecount += 4;
        }
    }
    catch (IOException)
    {
        if (Settings.loglevel > 1)
        {
            Console.WriteLine("文件被其他应用占用,跳过当前条目");
        }
        // 跳过当前条目,避免无限循环
        printerlinecount += 4;
    }
    catch (ArgumentOutOfRangeException)
    {
        if (Settings.loglevel > 1)
        {
            Console.WriteLine("文件内容不完整,终止读取");
        }
        break;
    }
}

关键修改点说明

  • 减少文件打开次数:无论是一次性读入还是单循环内单次打开,都避免了多次调用File.ReadLines重复打开文件的操作,从根源降低冲突概率。
  • 修复循环逻辑:捕获文件占用异常后主动递增printerlinecount,避免程序卡在原地无限重试。
  • 增加边界处理:针对文件行数不足的情况添加捕获逻辑,避免因索引越界导致未处理的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 16:39:21