Search code examples
c#access-deniedreadlines

Closing with "access denied" even with try-catch


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


Solution

  • You have to catch all exceptions, not only IOException:

    catch (Exception)