I want to check if particular text already exists in a csv file.
Is there any way or function except storing the whole file into variable and comparing each of its contents with the target text?
CodePudding user response:
Assuming you don't care about checking for delimiters, etc. and (importantly) you never need to search for text that contains a newline, you could use File.ReadLines
and .Contains
to check for a specific text:
string fileName = "myFile.csv";
string textToFind = "bob";
bool hasText = File.ReadLines(fileName)
// .Skip(1) // uncomment this line if your file has a header you wish to skip
.Any(l => l.Contains(textToFind, StringComparison.Ordinal));
You can change StringComparison.Ordinal
to StringComparison.OrdinalIgnoreCase
if you want a case insensitive search.
File.ReadLines
reads the file line-by-line as .Any
is evaluated, so you don't have to load the entire file into memory in one go, and .Any
will exit early if a match is found, so the file will stop being read at that point.
Note that for older versions of .NET, .Contains
doesn't have an overload that takes a StringComparison
so in that case you can only use .Any(l => l.Contains(textToFind));
CodePudding user response:
Just use ReadAllText function and use regex or find to check exist particular text