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()) !=
            null) 
            { if (!(line)) 
            StrBld.AppendLine(line.Replace(' ',',')); 
            } 


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




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


//WRITING DESTINATION File



//WRITE the file and display it line by line.
 using (StreamWriter sw = new StreamWriter(tempFilename))
 {
    sw.WriteLine(StrBld.ToString());
 }
file.Close();



Please share your thoughts and comments for the dame



2 comments:

  1. The blog is absolutely fantastic. Lots of great information and inspiration, both of which we all need. Thanks.

    PIC Scheme Singapore

    ReplyDelete

Thanks for your valuable comments

Rate Now: