C# Cannot implicitly convert type 'string' to 'System.IO.StreamReader
14,709
Solution 1
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();
Solution 2
File.ReadAllText
actually reads the whole file into a string. Try File.OpenRead
instead
Author by
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
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(); }
-
Viktor Vix Jančík over 14 yearsWhy are you forcing the encoding in ReadAllText()?
-
-
Rob Fonseca-Ensor over 14 yearsDo you mean File.ReadAllLines? This method is easier but if the file is huge the whole thing will be loaded into memory...
-
Admin over 14 yearsError 1 Cannot implicitly convert type 'string' to 'string[]' @ string[] lines = File.ReadAllText(filex.FullName, Encoding.Unicode);
-
Powerlord over 14 yearsInstead of
File.OpenRead
, wouldn't he wantFile.OpenText
?