简体   繁体   中英

Can't read file using File.ReadAllLines

I am trying to make a button check each line of the file in openFileDialog1.FileName and if it contains one of the strings, "LCD" or "laser" and "on" on the same line, or if it contains "laser" and "off" on the same line and the string ".end" and then do something.

I am new to C# (started this week) and that not a native English speaker either.

my goal is to make my Arduino Robot arm (my first build so its very simple) somewhat programmable, just to control the LCD and turn the laser on or off (so far).

BTW this is just the Simulator so that's why it never sends any serial data.

Below is a snippet of the code where the problem is, the problem is that when i "Run" the code in the simulator it seems to be checking all the lines at once because in the code it checks, which is

LCD = hello  
laser = on  
LCD = 000  
laser = off

it only sets the LCD to 000, i checked the laser = on code alone before and it didn't work in there but when i tried it in private void Form3_Load(object sender, EventArgs e) it worked perfectly , so bottom line The last LCD command in each code works and the laser code never works.

also i want to have every line represent 1 second, so each line will take one second before it continues on the next line.

the timer1 interval is 1000 (one second)

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

The problem here is that you want to put the code that does the File.ReadAllLines() outside of your code that gets called once a second timer1_Tick() . You're reading the entire file every time timer tick, when what you really want to do is just process one line of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM