Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

C# Search a file for text

  • 21-08-2009 3:32pm
    #1
    Registered Users, Registered Users 2 Posts: 99 ✭✭


    This might seem like me being a complete imbecele but I'm just starting off coding in C# & Im having a bit of trouble with a string search.

    Im trying to open a file & search for a string that changes each day in the file. The string is two constant chars followed immediately by 4 variable digits (eg AB1234)

    The only way I can think is to use StreamReader to read each char into an array & then search the array until I find the first constant char, then I guess I would start a nested loop to search the following elements to see if they match what Im looking for. But I just cannot seem to figure it out.

    Anyone any ideas or code samples that might help me with this?

    Thanks


Comments

  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Regular expressions should help you here.


  • Closed Accounts Posts: 48 Ronan_


    How much of it have you got done and what type of file is it?

    Use streamreader to read all of the text into a string variable.
    Then you could try something like .IndexOf("ab") on the string to return the position of the first occurance of the two constant characters and then read the four digits after it.


  • Registered Users, Registered Users 2 Posts: 2,931 ✭✭✭Ginger


    Be far the easiest way to do this is using the Regex.Matches function in C# (http://msdn.microsoft.com/en-us/library/e7sf90t3.aspx) sits in the Namespace System.Text.RegularExpressions. It has 4 overloads such as supplying a Regex Options to do stuff such as ignore case etc (http://msdn.microsoft.com/en-us/library/b49yw9s8.aspx).

    Read the file in as a string, and then do a regular expression match to find it. It will return a list of matches that match your criteria . You can then use a simple foreach statement to loop through all the matches if there are any and do what you need.

    To read in the file well here is an example http://www.csharp-examples.net/load-text-file-to-string/


Advertisement