29

我是 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 窗体应用程序中的正确文本框。我无法理解如何正确执行此操作。我需要使用流式阅读器吗?或者在这种情况下还有另一种更好的方法吗?谢谢你。

4

2 回答 2

40

这是一种方法:

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);
        }
    }
}
于 2013-04-21T21:38:48.323 回答
7

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

using System.IO;

接下来的代码包含两种读取文本的方法,第一种将读取单行并将它们存储在字符串变量中,第二个读取整个文本并将其保存在字符串变量中(包括“\n”(输入))

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


    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(" ") 并使用循环将名称放回一个字符串中。如果您不想使用 .Split() 那么您也可以使用 foreach 并添加一个 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(如果它们是公共的并且有 get 这将起作用)。

于 2018-01-28T14:27:35.077 回答