在windows窗体中使用OpenFileDialog读取文本文件
本文关键字:OpenFileDialog 读取 取文本 文件 windows 窗体 | 更新日期: 2023-09-27 18:10:19
我是OpenFileDialog函数的新手,但已经弄清楚了基本知识。我需要做的是打开一个文本文件,从文件中读取数据(仅文本),并正确地将数据放入应用程序中的单独文本框中。下面是我的"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());
}
}
我需要阅读的文本文件是这样的(作为家庭作业,我需要阅读这个文件),它有员工编号、姓名、地址、工资和工作时间:
1
John Merryweather
123 West Main Street
5.00 30
在我得到的文本文件中,有4个员工的信息紧随其后,格式相同。您可以看到员工的工资和工作时间在同一行,而不是打字错误。
这里有一个employee类:
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窗体应用程序中的正确文本框。我很难理解如何正确地做这件事。我需要使用流媒体阅读器吗?或者在这种情况下还有其他更好的方法吗?谢谢你。
有一种方法:
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
EDIT这里有另一种更适合您需求的方式:
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);
}
}
}
对于这种方法,您需要添加system。通过在c#文件顶部附近的其他引用下面添加下一行代码(其中其他使用****。* *站)。
using System.IO;
接下来的代码包含2种读取文本的方法,第一个将读取单行并将其存储在字符串变量中,第二个将读取整个文本并将其保存在字符串变量中(包括"'n"(enter))
都应该很容易理解和使用。
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;
}
或者您可以通过在实例名后面键入. variableame来使用集合添加它(如果它们是公共的并且有一个集合,这将工作)。要读取数据,您可以通过在实例名后面键入. variableame来使用get(如果它们是公共的并且具有get,则可以使用)。
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFileDialog.ShowDialog()== DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog.FileName);
}