Reputation: 569
I have a strange problem with StreamReader. My program is a console program and it should loop through a directory structure for all *.cs file. Then check if a specific word is in the file and write the file path to output.
using (StringReader sr = new StringReader(fPath))
{
string content = sr.ReadLine(); // sr.ReadToEnd();
Debug.WriteLine(content);
int found = content.IndexOf(p);
if (found != -1)
{
result = true;
}
}
This is the code that I use to find the work in a specific file. The problem is that sr.ReadToEnd (but also ReadLine) returns the value of fPath not the content of the file!
The file exists and is not locked.
If fPath is: "C:\TEMP\DC_LV1_LaMine_Mk2Plus_134_ix220_20160404\Alarm.Script.cs"
content will be: "C:\TEMP\DC_LV1_LaMine_Mk2Plus_134_ix220_20160404\Alarm.Script.cs"
Can anyone see what I have done wrong?
Upvotes: 0
Views: 1172
Reputation: 3443
You are using StringReader instead of StreamReader
StringReader implements a TextReader that reads from a string
StramReader implements a TextReader that reads characters from a byte stream in a particular encoding
If you want to read from a file use this constructor for StreamReader
You could also use File.ReadAllText if the file is small and you have enough resources to read it all at once
For a more comprehensive overview, see this article
Upvotes: 5