Reputation: 3515
I want to check file content for a particular string, actually I want to check is file contains 'ANSWER
' and if there some character of anything after that string to the end of file.
How can I achive that?
p.s. file content is dynamic content and that 'ANSWER' string is not on fixed location inside file.
Thanks
Upvotes: 1
Views: 66
Reputation: 133950
One way is to load the entire file into memory and search it:
string s = File.ReadAllText(filename);
int pos = s.IndexOf("ANSWER");
if (pos >= 0)
{
// we know that the text "ANSWER" is in the file.
if (pos + "ANSWER".Length < s.Length)
{
// we know that there is text after "ANSWER"
}
}
else
{
// the text "ANSWER" doesn't exist in the file.
}
Or, you can use a regular expression:
Match m = Regex.Match(s, "ANSWER(.*)");
if (m.Success)
{
// the text "ANSWER" exists in the file
if (m.Groups.Count > 1 && !string.IsNullOrEmpty(m.Groups[1].Value))
{
// there is text after "ANSWER"
}
}
else
{
// the text "ANSWER" does not appear in the file
}
In the regex case, the position of "ANSWER" would be in m.Index
, and the position of the text after "ANSWER" would be in m.Groups[1].Index
.
Upvotes: 2
Reputation: 460028
static bool containsTextAfter(string text, string find)
{
// if you want to ignore the case, otherwise use Ordinal or CurrentCulture
int index = text.IndexOf(find, StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
int startPosition = index + find.Length;
if (text.Length > startPosition)
return true;
}
return false;
}
use it in this way:
bool containsTextAfterAnswer = containsTextAfter(File.ReadAllText("path"), "ANSWER");
Upvotes: 6