我正在用 C# 构建一个 Winforms 应用程序,我将读入 3 个文件,然后迭代它们以执行一些功能来验证它们。在学习 Winforms 和 C# 时,我无法迭代并且似乎无法弄清楚。
// store each file path into a string
string nailAssignmentResult = textBox1.Text;
string nailFixtureResult = textBox2.Text;
string nailContactResult = textBox3.Text;
上面的声明将 3 个文本框的文件路径存储到字符串变量中,供我迭代。
我已经尝试过 foreach 循环和 for 循环,但我似乎无法弄清楚如何遍历它们。我想将每个文件中的信息解析成以空格分隔的列表。
namespace FixtureReports
{
public partial class btnFileSelect : Form
{
// contructor
public btnFileSelect()
{
InitializeComponent();
}
// this will do the verification
private void btnVerify_Click(object sender, EventArgs e)
{
// clear textbox each time its clicked
results.Clear();
//store each file path into a string
string nailAssignmentResult = textBox1.Text;
string nailFixtureResult = textBox2.Text;
string nailContactResult = textBox3.Text;
// error for if all three paths are empty
TextBox errorMessage = results;
if (nailAssignmentResult == "" && nailFixtureResult == "" && nailContactResult == "")
errorMessage.Text = "ERROR: Cannot have empty path for all three reports!!";
// verifying each file path exists
if (File.Exists(nailAssignmentResult))
errorMessage.AppendText("Nail Assignment Report Found");
if (File.Exists(nailFixtureResult))
errorMessage.AppendText("\r\nNail Fixture Report Found");
if (File.Exists(nailContactResult))
errorMessage.AppendText("\r\nNail Contact List Report Found");
// grab each file and iterate through each of them
// parse the contents into a list separated by a space horizontally
// for each line of data, what needs to be compared
// take in receiver pin and plug into brians function to get pylon
// compare to existing pylon designation in report and see if it matches
// have a counter for how many were correct
// if incorrect, display pylon blocks and receiver pins
}
// prompt for file selection
private void nailFixtureBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog.FileName;
}
}
// prompt for file selection
private void nailAssignmentBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
textBox2.Text = openFileDialog.FileName;
}
}
// prompt for file selection
private void nailContactBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
textBox3.Text = openFileDialog.FileName;
}
}
}
}
为了“迭代”你需要一个集合。您可以从三个变量创建一个简单的数组:
var files = new[] {nailAssignmentResult, nailFixtureResult, nailContactResult};
并迭代 that,但是如果您在一个函数中有“处理”,您可以只传入文件名(以及需要的任何其他信息,那么您不需要需要迭代:
var assignmentResults = ProcessFile(nailAssignmentResult);
var fixtureResults = ProcessFile(nailFixtureResult);
var contractResults = ProcessFile(nailContactResult);
这只是两个选项 - 有很多方法可以做到这一点,包括创建一个使用
yield return
返回每个值的迭代器函数,但我认为不需要任何比值的简单数组更高级的东西。
从这个开始:
foreach( var line in File.ReadLines(nailAssignmentResult))
{
// ...
}
在深入之前,您需要编写更多自己的代码,并清楚规范。
另外:不要检查
File.Exists()
!存在只是您可能无法打开文件的多种原因之一。此外,文件系统是 volatile,这意味着文件的状态可以在您检查它和尝试打开它之间的短时间内发生变化。出于这个原因,您必须能够在尝试打开文件时处理异常,而不管之前是否进行过任何检查。
因此
Exists()
检查实际上只是归结为额外的不必要(浪费)的 I/O 操作,而磁盘 I/O 是您可以在单台计算机上执行的最慢的事情之一。在几乎所有情况下,最好只将精力放在异常处理程序上。
要遍历这三个文件,您可以使用 foreach 循环并将文件路径存储在数组或列表中。这是一个示例,说明如何修改 btnVerify_Click 方法以遍历文件并读取其内容:
private void btnVerify_Click(object sender, EventArgs e)
{
// clear textbox each time its clicked
results.Clear();
// store each file path into a string
string[] filePaths = { textBox1.Text, textBox2.Text, textBox3.Text };
// check if all three paths are empty
if (string.IsNullOrEmpty(filePaths[0]) && string.IsNullOrEmpty(filePaths[1]) && string.IsNullOrEmpty(filePaths[2]))
{
results.Text = "ERROR: Cannot have empty path for all three reports!!";
return;
}
// check if each file exists
foreach (string filePath in filePaths)
{
if (string.IsNullOrEmpty(filePath))
{
continue;
}
if (!File.Exists(filePath))
{
results.AppendText($"File {filePath} not found.\r\n");
return;
}
}
// iterate through each file
foreach (string filePath in filePaths)
{
if (string.IsNullOrEmpty(filePath))
{
continue;
}
// read the file contents and split by space
string[] lines = File.ReadAllLines(filePath);
List<string> items = new List<string>();
foreach (string line in lines)
{
items.AddRange(line.Split(' '));
}
// perform some function to verify the items in the list
// ...
// display the results
results.AppendText($"File {filePath} verified successfully.\r\n");
}
}
在这个例子中,我使用了一个数组来存储文件路径,但如果你愿意,你也可以使用一个列表。 foreach 循环用于遍历每个文件路径并检查文件是否存在。如果任何文件路径为空,则循环使用 continue 关键字跳到下一次迭代。如果未找到任何文件,则会显示错误消息并返回该方法。否则,将使用另一个 foreach 循环遍历每个文件并读取其内容。每个文件的内容按空格分割并存储在列表中,可用于进一步处理。最后,会显示一条消息,表明每个文件都已成功验证。