1

I have some Linq that searches for a key word in a text file, skips three rows when it finds it and then returns all rows below until it reaches a row that equals a double space.

var line = File.ReadLines(path)
            .SkipWhile(line => !line.Contains(searchText))
            .Skip(3)
            .TakeWhile(line => !line.Equals("  "));

I’d like to add some error handling in there, for example if the key word can’t be found or there aren’t three rows to skip through.

I was trying to apply this answer but I can’t get the Syntax right. Is it possible to handle exceptions within LINQ queries?

This is what I know have, but it still seems to throw an error System.IO.IOException' in System.Private.CoreLib.dll when the string can not be found in the text file.

What am I doing wrong here?

var line = File.ReadLines(path)
            .SkipWhile(line => !line.Contains(searchText))
            .Skip(3)
            .TakeWhile(line => 
            {
                try
                {
                    return !line.Equals("  ");
                }
                catch (Exception)
                {
                    return false;
                    //
                }
            });
Richard
  • 439
  • 3
  • 25
  • 2
    What is the exception exactly? It looks like it isn't being thrown by `line.Equals`, in which case that `try/catch` won't catch it – canton7 Mar 08 '22 at 14:37
  • What should you do in case of errors (file incorrect format): now you return empty enumerator if `searchText` is not found or it's found too late (if there's too few lines before end). – Dmitry Bychenko Mar 08 '22 at 14:38
  • 2
    I am quite sure that `File.ReadLines(path)` throws the exception and not your LINQ code. – SomeBody Mar 08 '22 at 14:45
  • You are correct. I was struggling to read errors from another thread, but finally found the error to be the dreaded "in use by another process". This is tricky because the files are created by a third party dll that doesn't seem to want to let them go. Problems!!! – Richard Mar 08 '22 at 17:21
  • Check out this solution to check for file locks https://stackoverflow.com/a/937558/2883319 – Carlo Bos Mar 11 '22 at 18:34

0 Answers0