Reputation: 1489
I am currently wanting to be able to cycle through a text file looking for a specific string, in my case: "mp4:production/
When the string has been matched (the file will be updated periodically - so the string won't necessarily be present at first), its line (in the text file) can then be output e.g. in a messagebox
How could this be achieved, any examples would be appreciated
Upvotes: 0
Views: 108
Reputation: 1
If you want to block the thread by calling sleep, you should first create a new thread to do the file reading on. You can use a System.Threading.Timer: http://msdn.microsoft.com/en-us/library/swx5easy.aspx
Upvotes: 0
Reputation: 700152
You would have to loop and read the file repeatedly.
Note that you need some error handling, as it's quite likely that the file will be unaccessible sometimes because some other process is writing to it.
bool found = false;
while (!found) {
try {
found = File.ReadAllText(fileName).Contains(searchString);
} catch (IOException) {
// I/O error, occurs if the file is being written.
// Nothing to do here, just wait and retry.
}
if (!found) {
Thread.Sleep(5000);
}
}
The code above assumes that the file is reasonably small so that it can all be read into memory. If the file is very large you would have to read it in smaller chunks to avoid out of memory exceptions.
The code is waiting 5 seconds (5000 milliseconds) between each try. You should adjust the time depending on your specific situation, i.e. how often you can check the file while still keeping the risk reasonably small that it disturbes the process that is trying to change the file.
Upvotes: 0
Reputation: 6223
while(true) {
Thread.Sleep(500); // lets get a break
if(!System.IO.File.Exists(FILE_NAME)) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText(FILE_NAME))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if(s.Contains(TEXT_TO_SEARCH)) {
// output it
}
}
}
}
Upvotes: 1