C# 在 Windows 窗体中使用 OpenFileDialog 读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16136383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a text file using OpenFileDialog in windows forms
提问by xavi
I am new to the OpenFileDialog function, but have the basics figured out. What I need to do is open a text file, read the data from the file (text only) and correctly place the data into separate text boxes in my application. Here's what I have in my "open file" event handler:
我是 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());
}
}
The text file I need to read is this (for homework, I need to read this exact file), It has an employee number, name, address, wage, and hours worked:
我需要阅读的文本文件是这样的(对于家庭作业,我需要阅读这个确切的文件),它包含员工编号、姓名、地址、工资和工作时间:
1
John Merryweather
123 West Main Street
5.00 30
In the text file I was given, there are 4 more employees with info immediately after this in the same format. You can see that the employee wage and hours are on the same line, not a typo.
在我得到的文本文件中,紧随其后的还有 4 名员工以相同的格式提供信息。您可以看到员工工资和工时在同一行上,而不是打字错误。
I have an employee class here:
我在这里有一个员工课程:
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
}
}
So I need to pull the text from that file into my Employee class, then output the data to the correct textbox in the windows forms application. I am having trouble understanding how to do this right. Do I need to use a streamreader? Or is there another, better way in this instance? Thank you.
所以我需要将该文件中的文本提取到我的 Employee 类中,然后将数据输出到 windows 窗体应用程序中的正确文本框。我无法理解如何正确执行此操作。我需要使用流阅读器吗?或者在这种情况下还有另一种更好的方法吗?谢谢你。
回答by jordanhill123
Here's one way:
这是一种方法:
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);
}
}
Modified from here:MSDN OpenFileDialog.OpenFile
从这里修改:MSDN OpenFileDialog.OpenFile
EDITHere's another way more suited to your needs:
编辑这是另一种更适合您需求的方式:
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);
}
}
}
回答by TeD van Loon
for this approach, you will need to add system.IO to your references by adding the next line of code below the other references near the top of the c# file(where the other using ****.** stand).
对于这种方法,您需要通过在靠近 c# 文件顶部的其他引用下方添加下一行代码来将 system.IO 添加到您的引用中(另一个使用 ****.** 的位置)。
using System.IO;
this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))
接下来的代码包含两种读取文本的方法,第一种读取单行并将它们存储在字符串变量中,第二个读取整个文本并将其保存在字符串变量中(包括“\n”(输入))
both should be quite easy to understand and use.
两者都应该很容易理解和使用。
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
}
}
}
To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.
要拆分文本,您可以使用 .Split(" ") 并使用循环将名称放回一个字符串中。如果你不想使用 .Split() 那么你也可以使用 foreach 并添加一个 if 语句来在需要的地方拆分它。
to add the data to your class you can use the constructor to add the data like:
要将数据添加到您的类中,您可以使用构造函数添加数据,例如:
public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
{
EmployeeNum = EMPLOYEENUM;
Name = NAME;
Address = ADRESS;
Wage = WAGE;
Hours = HOURS;
}
or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).
或者您可以通过在实例名称后键入 .variablename 来使用集合添加它(如果它们是公共的并且有一个集合,这将起作用)。要读取数据,您可以通过在实例名称后键入 .variablename 来使用 get(如果它们是公开的并且有 get 这将起作用)。

