从文本文件命令中获取值

时间:2013-10-24 07:02:30

标签: c#

我有一个小问题,我无法弄清楚。我有一个代码,会读取文本文件。当我读取文本文件时,文件中有命令。此命令用于连接到串行端口的泵。所以我要做的就是让所有命令通过串口发送它们。我可以做到这一点,但现在我必须做一个wait(value)命令。 wait命令的值总是不同的。所以我必须得到wait命令的value,然后我将wait命令的值放入Thread.Sleep(waitvalue)。所以waitvalue是wait命令的值。

这是我读取文本文件的代码:

Stream mystream;
        OpenFileDialog commandFileDialog = new OpenFileDialog();

        if (commandFileDialog.ShowDialog() == DialogResult.OK)
        {
            if ((mystream = commandFileDialog.OpenFile()) != null)
            {
                string fileName = commandFileDialog.FileName;
                CommandListTextBox.Text = fileName;

                string[] readText = File.ReadAllLines(fileName);
                foreach (string fileText in readText)
                {
                    _commandList.Add(fileText);
                }
                CommandListListBox.DataSource = _commandList;

            }
        }

_commandlist是一个StringList。 StringList是我的同事的一个函数,在这个函数中你将有一个字符串列表。 在stringlist中,我将把文件放在文件中。 然后我将_commandlist作为我的列表框的数据源。

这是运行命令的代码,这是我尝试从wait命令获取值的代码的一部分。但我无法弄清楚如何获得价值。

_comport.PortName = "COM6";
        _comport.Open();
        foreach (string cmd in _commandList)
        {
            if (cmd.Contains("WAIT"))
            {
                //Action

            }
            _comport.Write(cmd + (char)13);
            Thread.Sleep(4000);

        }
        _comport.Close();

Thread.Sleep(4000)我必须用我的等待值替换4000。

部分文本文件:
RUN
WAIT(1000)
STOP
WAIT(1600)
RUNW
WAIT(4000)
STOP

有人可以帮我吗? 提前致谢

1 个答案:

答案 0 :(得分:1)

试试这个:

foreach (string cmd in _commandList)
{
    if (cmd.StartsWith("WAIT"))
    {
        //Action
    }
    _comport.Write(cmd + (char)13);
    int wait = 0;
    var waitString=cmd.Substring(cmd.IndexOf('(') + 1, 
        cmd.IndexOf(')') - cmd.IndexOf('(') - 1);
    if (Int32.TryParse(waitString, out wait))
    {
        Thread.Sleep(wait);
    }
}

<强> [编辑]

我不确定我是否完全理解处理逻辑,但这是我对代码结构的最佳猜测。

// iterate through the commands
foreach (string cmd in _commandList)
{
    // check if the current command is WAIT
    if (cmd.StartsWith("WAIT"))
    {
        int
            wait = 0, // the amount of milliseconds to sleep
            startPosition = cmd.IndexOf('(') + 1,
            length = cmd.IndexOf(')') - cmd.IndexOf('(') - 1;
        // check if the length of the string between '(' and ')' is larger then 0
        if (length > 0)
        {
            var waitString = cmd.Substring(startPosition, length);
            // check if the string between '(' and ')' is an integer
            if (Int32.TryParse(waitString, out wait))
            {
                // sleep for 'wait' milliseconds
                Thread.Sleep(wait);
            }
        }
    }
    // current command is not WAIT
    else
    {
        // send it to the COM port
        _comport.Write(cmd + (char)13);
    }
}