我目前正在開發一個項目。但我並不擅長C#。我需要做的是打開一個G代碼文件並從中讀取數據並通過USB將它發送給CNC機器。我可以讀取數據併發送。但現在我想讀取一行並通過USB發送,然後讀取下一行。下面我附上了我用來讀取G代碼文件和其他相關數據的代碼。一次只讀一行
開G代碼文件和讀取到一個文本框的所有數據:
private void btnopen_Click(object sender, EventArgs e)
{
//OpenFileDialog1.ShowDialog();
OpenFileDialog file = new OpenFileDialog();
file.FileName = "";
file.Title = "Open A Text document.";
file.Filter = "(*.gc)|*.gc|(*.etf)|*.etf|(*.txt)|*.txt|(*.GC)|*.GC|(*.tap)|*.tap";
DialogResult result = file.ShowDialog();
if (result == DialogResult.OK)
{
System.IO.StreamReader OpenFile = new System.IO.StreamReader(file.FileName);
textBox1.Text = OpenFile.ReadToEnd();
OpenFile.Close();
}
讀XYZ從打開的文件座標:
private void button1_Click(object sender, EventArgs e)
{
Regex Gcode = new Regex("[ngxyzf][+-]?[0-9]*\\.?[0-9]*", RegexOptions.IgnoreCase);
MatchCollection m = Gcode.Matches(this.textBox1.Text);
double X, Y, Z, F;
int g_code = 0;
int x_code = 0, y_code = 0, z_code = 0;
float x = 0, y = 0, z = 0;
foreach (Match n in m)
{
if (n.Value.StartsWith("G"))
{
g_code = Convert.ToInt32(ExtractNumbers(n.Value));
}
if (n.Value.StartsWith("X"))
{
x = float.Parse(ExtractNumbers(n.Value));
x = x * 1000;
x_code = Convert.ToInt32(x);
}
if (n.Value.StartsWith("Y"))
{
y = float.Parse(ExtractNumbers(n.Value));
y = y * 1000;
y_code = Convert.ToInt32(y);
}
if (n.Value.StartsWith("Z"))
{
z = float.Parse(ExtractNumbers(n.Value));
z = z * 1000;
z_code = Convert.ToInt32(z);
}
}
ExchangeInputAndOutputReports(g_code,x_code, y_code,z_code);
}
你看着TextReader.ReadLine? –
[從一行文件逐行讀取數據]的可能重複(http://stackoverflow.com/questions/15274917/read-data-from-a-file-line-by-line) –