在Windows窗体中使用OpenFileDialog读取文本文件

时间:2013-04-21 21:25:32

标签: c# openfiledialog

我是OpenFileDialog函数的新手,但已经找到了基础知识。我需要做的是打开一个文本文件,从文件中读取数据(仅文本)并正确地将数据放入我的应用程序中的单独文本框中。这是我在“打开文件”事件处理程序中的内容:

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)
    {
        MessageBox.Show(theDialog.FileName.ToString());
    }
}

我需要阅读的文本文件是这个(对于家庭作业,我需要阅读这个确切的文件),它有一个员工编号,姓名,地址,工资和工作小时数:

1
John Merryweather
123 West Main Street
5.00 30

在我给出的文本文件中,还有4名员工在此之后立即以相同的格式提供信息。您可以看到员工工资和工时都在同一条线上,而不是拼写错误。

我在这里有一个员工班:

public class Employee
{
    //get and set properties for each 
    public int EmployeeNum { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public double Wage { get; set; }
    public double Hours { get; set; }

    public void employeeConst() //constructor method
    {
        EmployeeNum = 0;
        Name = "";
        Address = "";
        Wage = 0.0;
        Hours = 0.0;
    }

    //Method prologue
    //calculates employee earnings
    //parameters: 2 doubles, hours and wages
    //returns: a double, the calculated salary
    public static double calcSalary(double h, double w)
    {
        int OT = 40;
        double timeandahalf = 1.5;
        double FED = .20;
        double STATE = .075;
        double OThours = 0;
        double OTwage = 0;
        double OTpay = 0;
        double gross = 0; ;
        double net = 0;
        double net1 = 0;
        double net2 = 0;
        if (h > OT)
        {
            OThours = h - OT;
            OTwage = w * timeandahalf;
            OTpay = OThours * OTwage;
            gross = w * h;
            net = gross + OTpay;
        }
        else
        {
            net = w * h;
        }

        net1 = net * FED; //the net after federal taxes
        net2 = net * STATE; // the net after state taxes

        net = net - (net1 + net2);
        return net; //total net
    }
}

所以我需要将该文件中的文本拉入我的Employee类,然后将数据输出到windows窗体应用程序中的正确文本框。我无法理解如何做到这一点。我需要使用流读取器吗?或者在这种情况下还有另一种更好的方法吗?谢谢。

2 个答案:

答案 0 :(得分:35)

这是一种方式:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

从此处修改:MSDN OpenFileDialog.OpenFile

编辑这是另一种更适合您需求的方式:

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)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

答案 1 :(得分:3)

对于这种方法,您需要将system.IO添加到您的引用中,方法是在c#文件顶部附近的其他引用下面添加下一行代码(其中另一行使用****。**代表)

using System.IO;

下一个代码包含2个读取文本的方法,第一个读取单行并将它们存储在字符串变量中,第二个读取整个文本并将其保存在字符串变量中(包括&#34; \ n& #34;(进入))

两者都应该很容易理解和使用。

    string pathToFile = "";//to save the location of the selected object
    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)
        {
            MessageBox.Show(theDialog.FileName.ToString());
            pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object

        }

        if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
        {
            //method1
            string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
            string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();

            //method2
            string text = "";
            using(StreamReader sr =new StreamReader(pathToFile))
            {
                text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
            }
        }
    }

要分割您可以使用的文本.Split(&#34;&#34;)并使用循环将名称放回一个字符串中。如果您不想使用.Split(),那么您也可以使用foreach和ad if语句将其拆分。

要将数据添加到您的类,您可以使用构造函数添加如下数据:

  public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
        {
            EmployeeNum = EMPLOYEENUM;
            Name = NAME;
            Address = ADRESS;
            Wage = WAGE;
            Hours = HOURS;
        }

或者您可以通过在实例名称后面键入.variablename来添加它(如果它们是公共的并且有一个设置,那么它将起作用)。通过在实例名称后键入.variablename来读取可以使用get的数据(如果它们是公共的并且得到它将起作用)。