-1

I have a C# program that most of the time works fine, but sometimes closes because the file is used by another application. I would like my program to just ignore whenever this happens, so I'm using try-catch whenever I use File.Readlines, but this code still fails:

while (printerlinecount < Gvalue.LineCount)
                {
                    try
                    {
                        string parameter = File.ReadLines(printerinfofile).Skip(printerlinecount).Take(1).First();
                        string parameterc = parameter.Trim(new Char[] { '[', ']' });
                        string printervalue = File.ReadLines(printerinfofile).Skip(printerlinecount + 2).Take(1).First();
                        string printervaluec = printervalue.Substring(6);
                        printerstatusvalues.Add(parameterc, printervaluec);
                        printerlinecount = printerlinecount + 4;
                    }

                    catch (IOException) { if (Settings.loglevel > 1) { Console.WriteLine("Access Denied (l)"); } }

                }

Anybody has an idea what I can do ?

best regards Steen

FujiSteen
  • 3
  • 2

1 Answers1

-1

You have to catch all exceptions, not only IOException:

catch (Exception)
i486
  • 6,491
  • 4
  • 24
  • 41
  • Perhaps `UnauthorizedAccessException`? – Enigmativity Feb 22 '23 at 08:02
  • @Enigmativity I explain why "code still fails". What will happen with `UnauthorizedAccessException` if file is missing? – i486 Feb 22 '23 at 08:58
  • Then you have another exception - however, it's easy to check if the file exists. It's almost always better to code around exceptions rather than let them rip. And you should only handle **specific** exceptions that you can **meaningfully** handle. – Enigmativity Feb 22 '23 at 10:50
  • If I code review someone who writes `catch (Exception)`, I will send them back to fix the code. It's an awful pattern. – Enigmativity Feb 22 '23 at 10:51
  • @Enigmativity What will happen without `catch (Exception)` - you prefer to see the default message box in unexpected cases? And what if reviewed code includes "most of the time works fine, but sometimes closes because the file is used by another application". Is it normal to handle this with try-catch? – i486 Feb 22 '23 at 12:08
  • "You prefer to see the default message box in unexpected cases?" Yes, but I prefer coders to code around exceptions so they never occur. – Enigmativity Feb 22 '23 at 12:26
  • "And what if reviewed code includes "most of the time works fine, but sometimes closes because the file is used by another application". Is it normal to handle this with try-catch?" Yes, with the specific exception - not `catch (Exception)`. – Enigmativity Feb 22 '23 at 12:27
  • I'm trying UnauthorizedAccessException, so far so good. The file is updated in this case, so missing file should not happen. – FujiSteen Feb 23 '23 at 10:17