Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
I HAVE A TEXT FILE NAMED C:/DATA.TXT WHICH CONTENTS LIKE THIS

36
12
45
66
76
89
77
66
54
...
...

SO ON

i NEED TO SEARCH IN ANOTHER TEXT FILE IN THE LOCATION BY TAKING INPUT FROM THE DATA.TXT ONE BY ONE.

2ND TEXT FILE IS LOOKING LIKE THIS :

A 21 AAAAAAA BCP
B 76 BBBBBBB MCR
C 77 CCCCCCC PHP
....
...

I NEED THE CONTENTS OF THE DATA.TXT TO BE SEARCHED IN THIS TEXT FILE AND IF FOUND THEN COPY THE WHOLE ROW TO ANOTHER TEXT FILE AND SAVE IT.

EXAMPLE : HERE 76 IS PRESENT IN THIS WHICH WAS PRESENT IN DATA.TXT SO I NEED TO COPY THE WHOLE LINE B 76 BBBBBBB MCR AND PASTE IT TO ANOTHER TEXT FILE AND SAVE IT ... HOW TO DO IT IN C SHARP. PLEASE HELP
Posted
Comments
Sergey Alexandrovich Kryukov 6-May-14 3:20am    
Did anyone told you that it's not nice to shout on the Web (ALL-CAPS is considered shouting)?
—SA
King Fisher 8-May-14 1:56am    
make it as lowercase

You can use File.ReadAllLines() and int.Parse() as index into the lines : http://www.dotnetperls.com/file-readalllines[^]
 
Share this answer
 
Can do it like below by using Linq
C#
var lines = File.ReadLines("d:\\data.txt");
File.WriteAllLines("d:\\data3.txt", 
		File.ReadLines("d:\\data2.txt").Where( l=> 
							lines.Contains(l.Split()[1])));


adding few more validations

C#
var lines = File.ReadLines("d:\\data.txt").Where(l=>!string.IsNullOrEmpty(l));
                    File.WriteAllLines("d:\\data3.txt",
                            File.ReadLines("d:\\data2.txt").Where(l =>!string.IsNullOrEmpty(l) && l.Split().Length >1 &&
                                                lines.Contains(l.Split()[1])));
 
Share this answer
 
v2
Comments
DEbopm 7-May-14 20:03pm    
File.Readlines is not supported in .net framework 3.5 .. Do you have a different solution ?
DEbopm 7-May-14 20:16pm    
If am trying to do it in 4.0 then the error is coming : in the last line
lines.contains(1.split()[1]))) - index was outside the bounds of the array
DamithSL 7-May-14 22:02pm    
you may have empty lines, or new line at the end of the text file.
there should be more than one item in each line separated by space, otherwise you will get exception
DamithSL 7-May-14 22:06pm    
check my updated answer with few validations
DEbopm 7-May-14 23:00pm    
it is not writing anything on data3.txt

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900