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((开发者_Python百科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();
}
File.ReadAllText
actually reads the whole file into a string. Try File.OpenRead
instead
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();
精彩评论