user1765862
user1765862

Reputation: 14165

found string at exact location in the file

I need to know is there some string at exact location on the .txt file. I know how to found concrete string with Contains method, but since I do not need to search whole file (string will always be on the same location) I'm trying to find quickest solution.

if (searchedText.Contains(item))
{
   Console.WriteLine("Found {0}",item);
   break;
}

Thanks

Upvotes: 0

Views: 99

Answers (2)

Wim Ombelets
Wim Ombelets

Reputation: 5265

if(searchedText.SubString(i, l).Contains(item))

where i is the starting index and l is the length of the string you're searching for.
Since you're using Contains, you have some margin in l.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502296

If it's in UTF-8 and isn't guaranteed to be ASCII, then you'll just have to read the relevant number of characters. Something like:

 using (var reader = File.OpenText("test.txt"))
 {
     char[] buffer = new char[16 * 1024];
     int charsLeft = location;
     while (charsLeft > 0)
     {
         int charsRead = reader.Read(buffer, 0, Math.Min(buffer.Length,
                                                         charsLeft));
         if (charsRead <= 0)
         {
             throw new IOException("Incomplete data"); // Or whatever
         }
         charsLeft -= charsRead;
     }
     string line = reader.ReadLine();
     bool found = line.StartsWith(targetText);
     ...
 }

Notes:

  • This is inefficient in terms of reading the complete line starting from the target location. That's simpler than looping to make sure the right data is read, but if you have files with really long lines, you may want to tweak this.
  • This code doesn't cope with characters which aren't in the BMP (Basic Multilingual Plane). It would count them as two characters, as they're read as two UTF-16 code units. This is unlikely to affect you.

Upvotes: 2

Related Questions