texto read net leer form ejemplo cargar archivo abrir c# openfiledialog

c# - read - Leyendo un archivo de texto usando OpenFileDialog en formularios de Windows



read file c# (2)

para este enfoque, deberá agregar system.IO a sus referencias agregando la siguiente línea de código debajo de las otras referencias cerca de la parte superior del archivo c # (donde está el otro ****. ** soporte).

using System.IO;

el siguiente código contiene 2 métodos para leer el texto, el primero leerá líneas simples y las almacenará en una variable de cadena, el segundo leerá todo el texto y lo guardará en una variable de cadena (incluyendo "/ n" (ingresa))

Ambos deben ser bastante fáciles de entender y 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 el texto puede usar .Split ("") y usar un bucle para volver a poner el nombre en una cadena. Si no desea usar .Split (), también puede usar foreach y ad una sentencia if para dividirla cuando sea necesario.

para agregar los datos a su clase, puede usar el constructor para agregar los datos como:

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

o puede agregarlo usando el conjunto escribiendo .variablename después del nombre de la instancia (si son públicos y tienen un conjunto, esto funcionará). para leer los datos, puede usar get escribiendo .variablename después del nombre de la instancia (si son públicos y tienen un get, esto funcionará).

Soy nuevo en la función OpenFileDialog, pero he descubierto lo básico. Lo que debo hacer es abrir un archivo de texto, leer los datos del archivo (solo texto) y colocar correctamente los datos en cuadros de texto separados en mi aplicación. Esto es lo que tengo en mi controlador de eventos "abrir archivo":

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

El archivo de texto que necesito leer es este (para la tarea, necesito leer este archivo exacto), tiene un número de empleado, nombre, dirección, salario y horas trabajadas:

1 John Merryweather 123 West Main Street 5.00 30

En el archivo de texto que recibí, hay 4 empleados más con información inmediatamente después en el mismo formato. Puede ver que el salario y las horas de los empleados están en la misma línea, no un error tipográfico.

Tengo una clase de empleados aquí:

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 lo tanto, necesito colocar el texto de ese archivo en mi clase de empleado y luego enviar los datos al cuadro de texto correcto en la aplicación de formularios de Windows. Estoy teniendo problemas para entender cómo hacer esto bien. ¿Necesito usar un streamreader? ¿O hay otra, mejor manera en este caso? Gracias.


Aquí hay una forma:

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 desde aquí: MSDN OpenFileDialog.OpenFile

EDITAR Aquí hay otra manera más adecuada a sus necesidades:

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