Question

I have the following type of data in a text file:

     Accumulated Earnings Tax. 
     A tax penalty which is imposed on corporate earnings which are retained by the corporation for non-
     business related needs. 

     Acquisition Cost. 
     The expenses incurred by an insurer or reinsurance company that are directly related to putting the 
     business on the books of the company. The largest portion of this cost is usually the agent's or sales 
     representative's commission or bonus. 

     Act of God. 
     An event arising out of natural causes with no human intervention which could not have been prevented 
     by reasonable care or foresight. Examples are floods, lightning, and earthquakes. 

     Actual Cash Value. 
     An amount equivalent to the replacement cost of lost or damaged property at the time of the loss, less 
     depreciation. With regard to buildings, there is a tendency for the actual cash value to closely parallel the 
     market value of the property. See also Market Value. 

every new word with the description has a line break! Now what i have to do is to read the file search the key word and print its description. The lines under the keyword but before the next word marked by a line break.

I have developed a code to find the keyword and print its description but it only prints the only one line of description!

My Code:

    int count = 1;
    private void openfile_Click(object sender, EventArgs e)
    {
        if (text.Text == String.Empty)
        {
            err.SetError(text, "Needs to contain Text");
        }

        DialogResult result = open_dialog.ShowDialog();

        if (result == DialogResult.OK)
        {

            try
            {
                string file_name = open_dialog.FileName;
                String lines_of_words;


                using (var file = System.IO.File.OpenText(file_name))
                {
                     // read each line, ensuring not null (EOF)
                    while ((lines_of_words = file.ReadLine()) != null)
                    {
                        if (lines_of_words.StartsWith(text.Text))
                        {

                            Console.WriteLine("TEXT IS YES"+count);
                            goGetDesc(file_name);
                            break;
                        }
                        else
                        {
                            count += 1;

                        }
                    }

                }
            }
            catch (Exception ex)
            {
            }
        }

    }

    private void goGetDesc(String file_name)
    {
        string[] lines = File.ReadAllLines(file_name);
        desc.Text+=(lines[count])+Environment.NewLine; //here i want to print the multiple lines if keyword has multiple lines!

    }

Suppose I want to find the keyword "Accumulated Earnings Tax. " and if its found i want to print all the lines under this keyword till the LINE BREAK.

Was it helpful?

Solution

Here is my solution:

using (StreamReader reader = File.OpenText("some file name"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        if (line.StartsWith(textBoxInput.Text, StringComparison.OrdinalIgnoreCase))
        {
            // At this point we've already read the keyword and it matches our input
            StringBuilder description = new StringBuilder(512);
            string descLine;
            // Here we start reading description lines after the keyword.
            // Because every keyword with description is separated by blank line
            // we continue reading the file until, the last read line is empty 
            // (separator between keywords) or its null (eof)
            while ((descLine = reader.ReadLine()) != string.Empty && descLine != null)
            {
                description.AppendLine(descLine);
            }
            textBoxDescription.Text = description.ToString();
            break;
        }
    }
}

Hope this helps.

OTHER TIPS

Here's another way to solve this, using regular expressions and reading the whole file at once (not line by line):

//using System.Text.RegularExpressions;

//the keyword you're looking for
String keyword = "Accumulated Earnings Tax";

//opening the file
using (StreamReader stream = File.OpenText("yourfile.txt"))
{
    //grabbing the whole content of the file at once
    String content = stream.ReadToEnd();                               

    //the regular expression, also see the regex101-link
    Regex re = new Regex("(" + keyword + "\\.).+?\n(.*\\.)");
    Match match = re.Match(content);
    if (match.Success)
    {
        //if the expression matches we can access our capturing groups
        //and extract the keyword and description
        Console.WriteLine("Keyword: " + match.Groups[1]);
        Console.WriteLine("Description: " + match.Groups[2]);
    }
}

Example at regex101.
Basically you make two capturing groups: one for the keyword, one for the description. After the keyword there has to be a ., perhaps one or more whitespace characters (.+?) and a newline (\n). After this follows the maingroup capturing the description until the last dot ((.*\\.)).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top