[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

searching string from a text file?

Posted on 2011-10-04
12
Medium Priority
?
299 Views
Last Modified: 2013-12-16
Hi,

I am trying find a string (it will be an URI) from a text file containing lines of URIs.
basically each line has an URI.

I was trying to use this Regex method but I am getting the unescape character problem.
 readFile = new System.IO.StreamReader("StatusLog.txt");
            string allRead = readFile.ReadToEnd();
            readFile.Close();

            //If the match is found in allRead
           
            if (Regex.IsMatch(allRead, fileName)
            {
                return true;
            }
            else
            {              
                return false;
            }


Is there a way to fix this problem?
I am looking at the Regex.Escape() but not sure how to use it.

Is there another way I can search the string?
Should I do while loop and readline(), then compare?
Can't think a better way to do this?
0
Comment
Question by:dkim18
  • 5
  • 5
  • 2
12 Comments
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36910866
Hello, have you tried:
if (allRead.IndexOf(fileName, StringComparison.InvariantCultureIgnoreCase) >= 0)
{
    return true;
}
else
{               
    return false;
}

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36910904
I agree with the above--I think a simple string search would be better for this purpose than would a regex. Unless you have some variance in your filenames, I can can't see any benefit to your using a regex.

I am looking at the Regex.Escape() but not sure how to use it.
Regex.Escape just parses the string you give it and escapes (i.e. adds a leading backslash to) any characters which have special meaning in regex-land. The return value of that function is the escaped string.

Should I do while loop and readline(), then compare?
If you have a really big file, then ReadLine would probably be more preferable; if your files are small, then ReadAll should be adequate.
0
 

Author Comment

by:dkim18
ID: 36911068
if (allRead.IndexOf(fileName, StringComparison.InvariantCultureIgnoreCase) >= 0)
{
    return true;
}
else
{              
    return false;
}

My file has these:
http://mysite.com/website1/
http://mysite.com/website2/
http://mysite.com/website2/subfolers/
http://mysite.com/website2/subfolers2/

if I was looking for http://mysite.com/website2/
Would  not the indexOf() bring back three result?
I need to exact match and bring back one result from above?


I
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:dkim18
ID: 36911136
readFile = new System.IO.StreamReader("StatusLog.txt");
            string allRead = readFile.ReadToEnd();
            readFile.Close();

            //If the match is found in allRead
           
            if (Regex.IsMatch(allRead, fileName)
            {
                return true;
            }
            else
            {              
                return false;
            }
readFile = new System.IO.StreamReader("StatusLog.txt");
            
          while ((line = readFile.ReadLine()) != null){
              
               if (line ==filename)
              {   return true; break;
               }
             }
             return fase;


something like this?

Open in new window

0
 
LVL 17

Assisted Solution

by:Carlos Villegas
Carlos Villegas earned 600 total points
ID: 36911159
Hello, based in the kaufmed sugestion, I think is better in this way:
using (System.IO.StreamReader sr = new System.IO.StreamReader("StatusLog.txt"))
{
    string myLine = sr.ReadLine();
    while (myLine != null)
    {
        if (myLine.IndexOf(fileName, StringComparison.InvariantCultureIgnoreCase) >= 0)
        {
            return true;
        }
        myLine = sr.ReadLine();
    }
    return false;
}

Open in new window

0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 1400 total points
ID: 36911219
Would  not the indexOf() bring back three result?
If you only call IndexOf once, then you will only get the first occurrence. If you want all occurrences, then you'll need to repeatedly call the method (i.e. loop). IndexOf is overloaded to take a start index as the second parameter. This is how you can skip the result(s) you just matched. For example:

using System.Collections.Generic;
using System.Linq;

namespace _27379331
{
    class Program
    {
        static void Main(string[] args)
        {
            System.IO.StreamReader readFile = new System.IO.StreamReader("StatusLog.txt");
            string find = "http://mysite.com/website2/";
            string input = readFile.ReadToEnd();
            int start = 0;
            List<string> matches = new List<string>();

            while ((start = input.IndexOf(find, start)) > 0)
            {
                string whitespace = "\n\r\t";
                int current = start;
                
                while (current < input.Length && !whitespace.Contains(input[current]))
                {
                    current++;
                }

                matches.Add(input.Substring(start, current - start));
                start = current;
            }
        }
    }
}

Open in new window


For what you are after, the whole URL, I have included a bit of logic to read, once the base URL is found, up to the next whitespace. This should return you the whole URL.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36911333
Hmmm...  I thought I had a space in my "whitespace" list. In case EE stripped it out, the whitespace variable should have a space in that list. I'll try again:

string whitespace = " \n\r\t";

Open in new window

0
 

Author Comment

by:dkim18
ID: 36911345
Sorry, how do you convert char to sring here?

!whitespace.Contains(input[current]))
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36911370
Sorry, how do you convert char to sring here?
Ah. I had Linq enabled, so I got a few extension methods! You can call the ToString method:

...!whitespace.Contains(input[current].ToString()))

Open in new window

0
 

Author Comment

by:dkim18
ID: 36911378
never mind.
 !whitespace.Contains(allRead[current].ToString()))
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36911386
You could also change that line to:

while (current < input.Length && whitespace.IndexOf(input[current]) < 0)

Open in new window

0
 

Author Closing Comment

by:dkim18
ID: 36911541
Thanks guys.
0

Featured Post

NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question