チーズパン
チーズパン

Reputation: 2778

How read out data from textfiles dynamically?

I've got a datastructure that contains several hundred coordinate points that look like this:

5,234   20,789
8,687   19,576
13,783   12,032
...

Each X and Y value is separated by TABs. They are always followed by additional information in textual form. Something like:

Date and Time: 22.04.2001
Software Version: 4.8.30002.0
....

For now there are always exactly 1024 coordinate points. So I simply read out coordinates for 1024 lines. Afterwards I am simply assuming that what follow is additional information so I am reading the stuff out to strings.

So the coordinate readout-loop looks something like this:

for(i=0;i<1024;i++)
{
   ReadXvalue();
   DoTab();
   ReadYvalue();
}

Now I want to read those files dynamically in case that points will be added or omitted. My first thought was just to check if the symbol I am reading is a number or a char. In case it is a number it must be a coordinate point. If it is a char I assume that it is additional information. In my opinion this is somehow dirty, or at least it doesn't feel right.
What would be a clean and smart way to do this?

Any examples, references or suggestions are welcome.

Greets, BC++

Upvotes: 0

Views: 143

Answers (4)

Davio
Davio

Reputation: 4737

You can even create your own tryParseCoordinates.

You can use this in combination with the mentioned StreamReader and process each line separately. If you use this method, you can make sure there are no dirty characters between or in the lines. As always, be wary of American vs. European decimal separators.

For instance this full example.

internal class Program
{
    private static void Main(string[] args)
    {
        double x, y;
        if (tryParseCoordinates("3,6\t2,4", out x, out y))
        {
            Debug.WriteLine(string.Format("X: {0}, Y:{1}",
                                          x.ToString(CultureInfo.InvariantCulture),
                                          y.ToString(CultureInfo.InvariantCulture)));
        }
    }

    private static bool tryParseCoordinates(string line, out double X, out double Y)
    {
        X = 0.0;
        Y = 0.0;

        string[] coords = line.Split(new[] {'\t'}, StringSplitOptions.RemoveEmptyEntries);
        if (coords.Length != 2)
        {
            return false;
        }

        bool xOk = double.TryParse(coords[0], out X);
        bool yOk = double.TryParse(coords[1], out Y);
        return xOk && yOk;
    }
}

Note that I'm using a European system, hence the comma as a decimal point.

Upvotes: 2

Yatrix
Yatrix

Reputation: 13775

You could also read the entire string -ReadToEnd(), I think- and use a regular expression to only grab the numbers. There should be plenty of examples out there on the actual expression. The regex class is a good one. This would be truly dynamic as long as all you ever wanted was the numbers. Tabs, strings - completely ignored.

Upvotes: 0

JSJ
JSJ

Reputation: 5691

If you have the fixed lenth columns which you have like (x, y) then i think this is more suitable way to read text files

   public DataTable GetDataTableFromTextFile(string filepath) 
    {
                                string line;
                                DataTable dt = new DataTable();                         
                                using (TextReader tr = File.OpenText(filepath))
                                {
                                    while ((line = tr.ReadLine()) != null)
                                    {
                                        string[] items = line.Split('\t');
                                        if (dt.Columns.Count == 0)
                                        {
                                            dt.Columns.Add(new DataColumn("FirstColumn", typeof(string)));
                                            dt.Columns.Add(new DataColumn("SecondColumn", typeof(string)));
                                            dt.Columns.Add(new DataColumn("ThridColumn", typeof(string)));

                                        }

                                        if (items.Length > 0 && !string.IsNullOrWhiteSpace(items[0].ToString()))
                                        {
                                            dt.Rows.Add(items);                                       
                                        }
                                    }
                                }
    return dt;

}

hope fully this will be helpful to you.

you can add columns as much as you want. and the dt.rows.add(item) will add only columns in the row as it has e.g item has only two items then the row will be added with two columns only.

Upvotes: 1

skaz
skaz

Reputation: 22580

Check out this example: http://www.dotnetperls.com/readline

You open up a SteamReader passing in the file that you are interested in. Then you can ReadLine which reads the next line, so you don't have to hardcode 1024 into your code. Then you can process each line individually.

Also, instead of `DoTab', check out String.Split You can also split on a tab, as seen here: http://msdn.microsoft.com/en-us/library/ms228388(v=vs.80).aspx

Upvotes: 1

Related Questions