/// /// Use a OpenFile common dialog to select a datafile and read data points. /// The points may be in one of two formats /// 1.) Each line contains two numbers separated by one or more /// spaces or tabs /// The first number is the x-coordinate, the second number /// is the y-coordinate /// 2.) Each line contains one number /// The numbers are all considered y-coordinates. /// The x-coordinate is implied by the line number. /// The x-coordinated of the first line is zero. /// The function returns an array of PointF objects. Each PointF /// contains an X and Y coordinate. /// PointF[] readGraphData(out float minX, out float maxX, out float minY, out float maxY) { // Use a common dialog box to get the file. OpenFileDialog dialog = new OpenFileDialog(); DialogResult dialogResult = dialog.ShowDialog(); PointF[] dataPoints = new PointF[0]; minX = 0.0f; maxX = 0.0f; minY = 0.0f; maxY = 0.0f; // If the user doesn't click OK, do nothing. if (dialogResult == DialogResult.OK) { // Open the selected file for reading. StreamReader reader = new StreamReader(dialog.OpenFile()); // There can be any number of spaces and/or tabs between x and y char[] separators = new char[] { ' ', '\t' }; // Read each line into nextLine. string nextLine; // Because we don't know how many points we will read, we read them // first into a List and then copy them to an array. List dataList = new List(); float nextX = 0; do { // Read a single line nextLine = reader.ReadLine(); // If it is a not a null or empty line if (!String.IsNullOrEmpty(nextLine)) { // Divide the line into fields string[] field = nextLine.Split(separators); // If there is only on value per line if (field.Length == 1) { // Use nextX for the x-coordinate and the read-in value for // the y-coordinate. dataList.Add(new PointF(nextX, Convert.ToSingle(field[0]))); nextX = nextX + 1.0f; } else { // if there is more than one field, use the first two for // x and y respectively. dataList.Add(new PointF(Convert.ToSingle(field[0]), Convert.ToSingle(field[1]))); } } } while (!reader.EndOfStream); // Close the file stream. reader.Close(); // If we read at least one point if (dataList.Count > 0) { // Create an array to hold the points dataPoints = new PointF[dataList.Count]; // Copy the list to the array int i = 0; foreach (PointF point in dataList) { dataPoints[i] = point; ++i; } } // Find the min and max values of x and y maxX = dataPoints[0].X; minX = dataPoints[0].X; maxY = dataPoints[0].Y; minY = dataPoints[0].Y; foreach (PointF point in dataPoints) { if (point.X < minX) minX = point.X; if (point.X > maxX) maxX = point.X; if (point.Y < minY) minY = point.Y; if (point.Y > maxY) maxY = point.Y; } } return dataPoints; }