Visual C# Developer Center > Visual C# Forums > Visual C# Language > Retrieving data in a text file...
Ask a questionAsk a question
 

AnswerRetrieving data in a text file...

  • Friday, November 06, 2009 11:23 AMDredgy Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    Hey all.

    Personal life been pretty screwed so am getting back into coding for fun.

    I'm creating a program that needs to read data from an external text file, separate the lines (each line contains a series of data) and then grab the values from the line.

    My text file structure looks similar to this, and I have the entire contents in a string:

    00000,80,9,120
    00001,40,2,290
    00002,50,7,600
    As you can probably see, the first column of data represents the ID/reference number of the row, while the latter 3 columns are actually data values.

    I can split the lines up into an array easily enough so it's somewhat like:
    data[1] = "00000,80,9,120";
    data[2] = "00001,40,2,290";
    data[3] = "00002,50,7,600";
    But what if I want to actually sort the tags.

    Say I want to grab row 2, I'd be matching the string against "^00001".

    So say I'm looping through my array, waiting for the string to match with the ID and then boom, it's matched.

    I do know the code to do this, but it failed and I got mad, something about an index exceeding its boundaries.

    So I'd like to hear your suggestions,

    Thanks a lot :D

Answers

  • Friday, November 06, 2009 11:56 AMGnanadurai Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code
    Hi,
    i hope it helps
     private void button1_Click(object sender, EventArgs e)
            {
               string value=ReadFile(textBox1.Text.ToString().Trim());
               MessageBox.Show(value);
            }
            
            private string ReadFile(string id)
            {
                using (StreamReader rdr = new StreamReader(@"c:\\file.txt"))
                {
                    string line;
                    while ((line = rdr.ReadLine()) != null)
                    {
                        if (Regex.IsMatch(line, id, RegexOptions.IgnoreCase))
                        {
                            return line;
                        }
                    }
                }
                return string.Empty;
            }
    

    Best Regards, C.Gnanadurai ----------------------- Please mark the post as answer if it is helpfull to you
    • Marked As Answer byDredgy Friday, November 06, 2009 12:07 PM
    •  
  • Friday, November 06, 2009 12:03 PMKelvinDavies11_Wales Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code

    Firstly you start by splitting the string values retrieved from the text file into a string array (this assume you have already done).

                foreach (string strLine in lines)<br/> 
    
    The above foreach loop, iterates through the string array, for for every string value it encounters it does the containing logic (the part inside the {}).

    string[] csv = strLine.Split(',');
    
    
    The above, splits the string line value, on the character ','.  So in essences you have a array of all the values in the string line. i.e. one string with the value 00000, one with 80 and so on.

    <pre lang="x-c#">ArrayList values = new ArrayList();foreach (string value in csv)
                    {
                        values.Add(value);
                    }
    
    The values array is then used to hold each of the string values.  The reason I have put them into a arraylist instead of leaving them in the string array, is because a arraylist has better search facilities.

    Now that you have all the values in a array list, you simply add this array to a hashmap, using the first value (id) in the arraylist as the key. 

    If this strill don't make sense please feel free to ask more questions, I am not the best atr explaining things, sorry.

    K

All Replies

  • Friday, November 06, 2009 11:40 AMKelvinDavies11_Wales Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    This may not be the best solution, but it is a starting point :)

    //Get string [] which represents each line of text
                //this string[] will be called lines
    
                Hashtable details = new Hashtable();
    
                foreach (string strLine in lines)
                {
                    string[] csv = strLine.Split(',');
                    ArrayList values = new ArrayList();
    
                    //Create arraylist of values
                    foreach (string value in csv)
                    {
                        values.Add(value);
                    }
    
                    //remove first value as this is the id
                    values.RemoveAt(0);
    
                    details.Add(csv[0], values);
    
                }
    
  • Friday, November 06, 2009 11:42 AMDredgy Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Cheers, looks pretty good. I'll have a crack at it now. :)


     EDIT: Ok, right. Basically I have no idea what this code is supposed to do. I've used foreach before, but only really in PHP. As a result I dunno what the foreach is doing. We;ll start with the obvious: what is str line? And how do I choose what ID I want to select from? And what will my final variable be (that I want to load into a textbox) Sorry, I'm not so good with the stuff I don't normally use, especially when I haven't written it myself. Thanks a load for your help
  • Friday, November 06, 2009 11:56 AMGnanadurai Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code
    Hi,
    i hope it helps
     private void button1_Click(object sender, EventArgs e)
            {
               string value=ReadFile(textBox1.Text.ToString().Trim());
               MessageBox.Show(value);
            }
            
            private string ReadFile(string id)
            {
                using (StreamReader rdr = new StreamReader(@"c:\\file.txt"))
                {
                    string line;
                    while ((line = rdr.ReadLine()) != null)
                    {
                        if (Regex.IsMatch(line, id, RegexOptions.IgnoreCase))
                        {
                            return line;
                        }
                    }
                }
                return string.Empty;
            }
    

    Best Regards, C.Gnanadurai ----------------------- Please mark the post as answer if it is helpfull to you
    • Marked As Answer byDredgy Friday, November 06, 2009 12:07 PM
    •  
  • Friday, November 06, 2009 12:03 PMKelvinDavies11_Wales Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code

    Firstly you start by splitting the string values retrieved from the text file into a string array (this assume you have already done).

                foreach (string strLine in lines)<br/> 
    
    The above foreach loop, iterates through the string array, for for every string value it encounters it does the containing logic (the part inside the {}).

    string[] csv = strLine.Split(',');
    
    
    The above, splits the string line value, on the character ','.  So in essences you have a array of all the values in the string line. i.e. one string with the value 00000, one with 80 and so on.

    <pre lang="x-c#">ArrayList values = new ArrayList();foreach (string value in csv)
                    {
                        values.Add(value);
                    }
    
    The values array is then used to hold each of the string values.  The reason I have put them into a arraylist instead of leaving them in the string array, is because a arraylist has better search facilities.

    Now that you have all the values in a array list, you simply add this array to a hashmap, using the first value (id) in the arraylist as the key. 

    If this strill don't make sense please feel free to ask more questions, I am not the best atr explaining things, sorry.

    K
  • Friday, November 06, 2009 12:06 PMDredgy Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Fantastic, with some tweaking for my project I have been able to get both methods to work quite well.

    Thank you both very muchly. :D
  • Friday, November 06, 2009 12:21 PMDheeraj_Mallemala Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi,

    use data table to store the data and column name to fetch the values.


    DataTable datatable;
            private void AddFileDataToTable() 
            {
                string FILELINE;
                datatable = new DataTable("Data");
                datatable.Columns.Add("ID");
                // use below code if "ID" column is always a numeric value
                //datatable.Columns.Add("ID", Type.GetType("System.Int32")); 
                
                datatable.PrimaryKey = new DataColumn[] { datatable.Columns["ID"] };
                datatable.Columns.Add("Column_1");
                datatable.Columns.Add("Column_2");
                datatable.Columns.Add("Column_3");

                
                using (System.IO.StreamReader file =             
                    new System.IO.StreamReader(@"C:\AddFileDataToTable.txt"))
                {
                    while ((file.Peek() > -1))
                    {
                        FILELINE = file.ReadLine().Trim();
                        if (FILELINE != string.Empty)
                            datatable.Rows.Add(FILELINE.Split(new char[] { ',' }));
                    }
                }

                DataRow datarow_array = datatable.Rows.Find("0001");
                // use below code if "ID" column is always a numeric value
                //DataRow datarow_array = datatable.Rows.Find(1); 
                if (datarow_array != null)
                    MessageBox.Show(datarow_array["Column_1"].ToString());
            }