views:

823

answers:

2

What i'm trying to do is open every text file in a directory, read it line by line, and if it matches a specific content, do a regex and output it to a result. For some reason my text files ended up being in unicode...., not sure dont know why. So I was able to work around that but I cant work around the stream reader issue i'm having. If someone could suggest a way to work around this it would be great, and if that way is to convert those text files, so be it.

heres the code:

        public void doSomeWork()
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\Documents and Settings\123");
        FileInfo[] Files = dinfo.GetFiles("*.txt");
        foreach (FileInfo filex in Files)
        {
            string line;
            StreamReader sr = File.ReadAllText(filex.FullName, Encoding.Unicode);
            StreamWriter sra = File.AppendText(@"C:\sharename.txt");
            int counter = 0;
            while((line = sr.ReadLine()) != null)
            {
                string matchingcontants = "Share";
                if (line.Contains(matchingcontants))
                {
                    string s = sr.ReadLine();
                    string sharename = Regex.Match(line, @"\+(\S*)(.)(.*)(.)").Groups[3].Value;
                    sra.WriteLine(sharename);
                }
                counter++;
            }
            sr.Close();
            sra.Close();  
        }
+6  A: 

File.ReadAllText actually reads the whole file into a string. Try File.OpenRead instead

Rob Fonseca-Ensor
Instead of `File.OpenRead`, wouldn't he want `File.OpenText`?
R. Bemrose
+3  A: 

File.ReadAllText returns a string containing all the text in the file.

Try changing:

StreamReader sr = File.ReadAllText(filex.FullName, Encoding.Unicode);

To

string[] lines = File.ReadAllLines(filex.FullName, Encoding.Unicode);

And changing

while((line = sr.ReadLine()) != null)

To

foreach(string line in lines)

And remove the following:

sr.Close();
Winston Smith
Do you mean File.ReadAllLines? This method is easier but if the file is huge the whole thing will be loaded into memory...
Rob Fonseca-Ensor
@Rob - thanks it was a copy and paste error. Now edited.
Winston Smith
Error 1 Cannot implicitly convert type 'string' to 'string[]' @ string[] lines = File.ReadAllText(filex.FullName, Encoding.Unicode);
Mike
ahh saw edit....
Mike