18 September 2012

Remove line with keyword from Text file :C#

Requirement : Huge text file needs to be parsed and the output file needs should eliminate
lines having special characters/words.

Solution: This is a 3 step solution : (1) reade file (2) Parse File with key word
(3) Output as required

Declare Source & Destination file - Setting parameter:

    string _SourceFile= @"c:\Sample_IN.txt";
    string _DestinationFile= @"c:\Sample_OUT.txt"; 

// Reading Source file

            string line =string.Empty; 
            StringBuilder StrBld= new StringBuilder();
            WrdFound = true; 
            //READ the file and display it line by line. System.IO.StreamReader
            file = new System.IO.StreamReader(filename); 
            while ((line = file.ReadLine()) !=
            { if (!(line)) 
            StrBld.AppendLine(line.Replace(' ',',')); 

//CHECK Key word against which the line to be dropped Ex my key words are "AKSHAYA"

            CheckKeyWord(string _eachLine) 
            if (_eachLine == null || _eachLine.Length
            == 0) return false; else 
            { Regex regex = new Regex(@"(AKSHAYA|MASHANKAR)", RegexOptions.IgnoreCase);
            return regex.IsMatch(_eachLine); } 


//WRITE the file and display it line by line.
 using (StreamWriter sw = new StreamWriter(tempFilename))

Please share your thoughts and comments for the dame

Rate Now: