简体   繁体   中英

Problems reading multiple lines from a text file and saving them into an array c#

So what I want to be able to do is read a file that has one data segment that reads like this. So far the program opens the file from a drop down menu but I am having a hard time saving them into array. I wish to be able to click a next button after opening the file (Where it prints the last three lines from the text file into the text boxes) on a form application, and it prints each information line in the text file example below into a separate text box. This is where I am having the problem.

The names and addresses are to be saved to a EmpNames Class, and then the .split() numbers below are to be saved into their own respective Employee Class so as to be set into a series of calculations, then print the result in a text box.

1
John MerryWeather
123 West Main Street
5.00 30

There will be multiple data segments like this, but no more than 10. This is what I have so far.

public partial class Form1 : Form
{
    const int MAX = 10;

    public Form1()
    {
        InitializeComponent();
    }


    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            //Declarations:
            //      linesPerEmployee: Controls the number of lines to be read.
            //      currEmployeeLine: Controls where in the file you are reading.

            Employee employee = new Employee();
            NameAdd empNames = new NameAdd();
            string filename = theDialog.FileName;



            List<Employee> employeeList = new List<Employee>();
            int linesPerEmployee = 4;
            int currEmployeeLine = 0;
            //parse line by line into instance of employee class


            while (employeeList != null)
            {
                string[] filelines = File.ReadAllLines(filename);
                if (filelines != null)
                {

                    employee.EmpNum = int.Parse(filelines[0]);
                    empNames.Name = 



                }
            }

Instead of reading all lines in one chunk you could read them line by line and add each line into a List<string> for example, to easier handle the "lines"

var employees = new List<string>();
Stream file = theDialog.File.OpenRead();
while((line = file.ReadLine()) != null)
{
    employees.Add(line);
}

And then loop through the employee list to parse each 4 lines into an Employee()

Still, I agree with the comments about using a better format instead.

too agree with the others about a better file format, but also, what happens if your data gets out of whack, missing or extra lines, any confirmation about sequence numbering between employees, bad data that can't be converted... all this and more say bad idea to current format.

However, that being said, and what you already have going, I would wrap it up something like...

string[] filelines = File.ReadAllLines(filename);
if (filelines != null)
{
    if (filelines.Length % 4 == 0)
    {
        // which array element are we getting to at the start of each employee.
        int arrayBase = 0;
        for( int i=0; i < (int)(filelines.Length / 4); i++ )
        {
            arrayBase = i*4;
            employee.EmpNum = int.Parse(filelines[arrayBase]);
            empNames.Name = filelines[arrayBase + 1];
            empNames.Address = filelines[arrayBase + 2];
            string[] rateAndHours = filelines[arrayBase + 3].Split(' ');
            // you would still have to parse the rate and hours though.
            double justRate = double.Parse(rateAndHours[0]);
            int justHours = int.Parse(rateAndHours[1]);
            // obviously add your own try\catch confirmation on parsing issues
            // and ultimately store in your record entries
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM