Reputation: 37
I presently have a multi line textBox that has acquired a list from another source.This list looks like this:
48:5D:36:4E:63:F8
00:24:1D:23:97:CF
4C:CC:6A:F4:42:2C
My Goal is:
I am trying to use the line items in this textBox list to find a match in a text file. What is important is when it does not find a line match in the text file, a messagebox appears saying "Item is not on list'...and include the actual textBox line item that wasn't found in the text file.
I am presently trying to work the following:
string find = textBox16.Text;
foreach (string line in File.ReadAllLines("watcher.txt"))
{
if (line.Contains(find))
{
//Do nothing
}
else
{
MessageBox.Show("Item not on list");
}
}
I've also tried this:
foreach (string line in textBox16.Lines)
{
if (File.ReadAllLines("watcher.txt").Contains(textBox16.Text))
{
//do nothing
}
else
{
MessageBox.Show("Item not on list");
}
}
I've tried several other ways, but nothing I have tried at this point is working correctly. Any help would be appreciated. Thanks~
Upvotes: 1
Views: 870
Reputation: 81513
Something like this i guess
var items = textBox16.Text
.Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
var lines = File.ReadAllLines("watcher.txt");
var missing = items.Where(item => !lines.Contains(item))
.ToList();
if(missing.Any())
MessageBox.Show($"Missing : \r\n {string.Join("\r\n", missing)}");
Note : There are more efficient ways to do this with larger files
Important comment from Dai
This assumes you want exact matches (as List.Contains(String) will call Object.Equals which will perform string ordinal-equality which may be undesirable, and won't match substrings.
I.e if your text file contains
48:5D:36:4E:63:F8
00:24:1D:23:97:CF
4C:CC:6A:F4:42:2C
...
and Case isn't a problem, then it should work
Upvotes: 1
Reputation: 155270
The problem is the textbox's text is not a single value: you're looking for multiple values on every line if the input text file.
You also don't need to read the entire file into memory (which is what ReadAllLines
does), you can read it line-by-line from a StreamReader
instead, this is how you can process multi-gigabyte sized text files while using minimal memory:
String[] findValues = this.textBox16.Text.Split( new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries );
List<Int32> matchingLineNumbers = new List<Int32>();
using( StreamReader rdr = new StreamReader( "watcher.text" ) )
{
String line;
Int32 lineNumber = 1;
while( ( line = rdr.ReadLine() ) != null )
{
foreach( String value in findValues )
{
if( line.IndexOf( value, StringComparison.OrdinalIgnoreCase ) > -1 )
{
matchingLineNumbers.Add( lineNumber );
}
}
lineNumber++;
}
}
if( matchingLineNumbers.Count == 0 )
{
MessageBox.Show( "Item not on list" );
}
else
{
String message = "Matching lines: " + String.Join( ", ", matchingLineNumbers.Select( n => n.ToString() ) );
MessageBox.Show( message );
}
Upvotes: 1