Ler um ficheiro de texto com o OpenFileDialog nos formulários do windows

Sou novo na função OpenFileDialog, mas tenho o básico resolvido. O que eu preciso fazer é abrir um arquivo de texto, ler os dados do arquivo (apenas texto) e corretamente colocar os dados em caixas de texto separadas na minha aplicação. Eis o que tenho no meu supervisor de eventos" open file":

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());
    }
}

o ficheiro de texto que preciso de ler é este( para os trabalhos de casa, preciso de ler este ficheiro EXACTO), tem um número de empregado, nome, endereço, salário e horas trabalhadas:

1
John Merryweather
123 West Main Street
5.00 30

no ficheiro de texto I foi dado, há mais 4 funcionários com info imediatamente após este no mesmo formato. Você pode ver que o salário do empregado e as horas estão na mesma linha, não um typo.

Tenho aqui uma aula de empregados.
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
    }
}

por isso, preciso de puxar o texto desse ficheiro para a minha classe de empregados, e depois enviar os dados para a caixa de texto correcta na aplicação formulários do windows. Estou a ter dificuldade em perceber como fazer isto bem. Preciso de usar um streamreader? Ou há outra maneira melhor de entrar? este caso? Obrigado.

Author: bryanmac, 2013-04-22

2 answers

Aqui está uma maneira:
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);
    }
}

Modificado a partir daqui:MSDN OpenFileDialog.OpenFile

Editar aqui está outra forma mais adequada às suas necessidades:

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);
        }
    }
}
 33
Author: jordanhill123, 2013-04-21 23:48:31

Para esta abordagem, terá de adicionar system.IO para suas referências, adicionando a próxima linha de código abaixo das outras referências perto do topo do arquivo C# (onde o outro usando*****.** estar).

using System.IO;

Este próximo código contém 2 métodos de leitura do texto, o primeiro irá ler linhas simples e armazená-las numa variável de texto, o segundo lê o texto inteiro e grava-o numa variável de texto (incluindo "\n" (entra)

Ambos devem ser muito fáceis de compreender e usar.


    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
            }
        }
    }

Para dividir o texto que pode usar .Dividir ( "" ) e usar um loop para colocar o nome de volta em uma string. se não quiseres usar .Split () então você também pode usar foreach e anúncio an if para dividi-lo onde necessário.


Para adicionar os dados à sua classe pode usar o construtor para adicionar os dados como:

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

Ou pode adicioná-lo usando o conjunto escrevendo .nome Variablen após o nome da instância(se eles são públicos e têm um conjunto isto vai funcionar). para ler os dados você pode usar o get digitando .nome Variablen após o nome da instância(se eles são públicos e têm um get isso vai funcionar).

 1
Author: TeD van Loon, 2018-01-28 14:27:35