2014-12-22 19 views
1

所以我想要做的就是读取一个文件,该文件具有一个像这样读取的数据段。到目前为止,程序从下拉菜单中打开文件,但我很难将它们保存到数组中。我希望能够在窗体应用程序中打开文件(它将文本文件的最后三行打印到文本框中)后单击下一个按钮,并将下面的文本文件示例中的每条信息行打印到单独的文本框。这是我遇到问题的地方。从文本文件中读取多行并将其保存到数组中的问题c#

姓名和地址将被保存到一个EmpNames类中,然后将下面的.split()数字保存到它们各自的Employee Class中,以便设置为一系列计算,然后将结果打印到文本框。

1 
John MerryWeather 
123 West Main Street 
5.00 30 

会有像这样的多个数据段,但不会超过10个。这是迄今为止我所拥有的。

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 = 



       } 
      } 
+0

指定与例如 –

+0

刚刚与一个简单的.txt文件的文件格式格式如上所示。将会有多个这样的四个线段,每个线段从1开始递增,然后是名称,地址和小时工资,然后是2,3等等。 –

+0

您可以使用skip跳过最后4行,并采用linq的扩展。然后把它们放在一个数组中 – Saravanan

回答

1

而不是读一个块都行,你可以通过在线阅读线,并添加每一行成List<string>例如,为了更容易处理,通过“线”

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

然后循环雇员名单解析每4行成Employee()

不过,我同意有关使用更好的格式,而不是意见。

0

太同意其他人关于更好的文件格式,但是,如果您的数据出现重击,丢失或多余的行,关于员工之间序列编号的确认,以及无法转换的错误数据,会发生什么情况。 ..所有这些和更多的说不好的想法,以目前的格式。

不过,话虽如此,并且你已经有打算,我会包起来像...

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 
     } 
    } 
} 
相关问题