【发布时间】:2014-11-06 22:32:12
【问题描述】:
我正在尝试制作一个按钮来检查 openFileDialog1.FileName 中文件的每一行,如果它包含字符串之一,“LCD”或“laser”和“on”在同一行,或者它是否包含“ Laser" 和 "off" 在同一行和字符串 ".end" 上,然后做一些事情。
我是 C# 的新手(本周开始),而且母语不是英语。
我的目标是让我的 Arduino 机器人手臂(我的第一个构建,所以它非常简单)有点可编程,只是为了控制 LCD 和打开或关闭激光(到目前为止)。
顺便说一句,这只是模拟器,所以它从不发送任何串行数据。
下面是问题所在代码的 sn-p,问题是当我在模拟器中“运行”代码时,它似乎同时检查了所有行,因为在它检查的代码中,即
LCD = hello
laser = on
LCD = 000
laser = off
它只将 LCD 设置为 000,我之前单独检查了激光 = 代码,但它在那里没有工作,但是当我在 private void Form3_Load(object sender, EventArgs e) 中尝试它时它工作得很好,所以底线每个 LCD 中的最后一个命令代码有效,激光代码永远无效。
我也想让每行代表 1 秒,所以每行需要一秒钟才能继续下一行。
timer1 间隔为 1000(一秒)
private void timer1_Tick(object sender, EventArgs e)
{
int lineNumber = richTextBox1.GetLineFromCharIndex(richTextBox1.TextLength);
string[] lines = File.ReadAllLines(openFileDialog1.FileName);
try
{
for (int i = 0; i < lineNumber; i++)
{
if (lines[i].Contains("LCD"))
{
label1.Text = lines[i].Remove(0, 6);
}
if (lines[i].Contains("laser") && lines[i].Contains("On"))
{
pictureBox4.Show();
}
if (lines[i].Contains("laser") && lines[i].Contains("Off"))
{
pictureBox4.Hide();
}
if (lines[i].Contains(".end"))
{
button2.PerformClick();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Form3", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
【问题讨论】:
-
您确定您已识别文件中的换行符吗?读完后打个断点,你可以将鼠标悬停在
lines上以查看其内容。
标签: c# .net loops for-loop file.readalllines