AI智能
改变未来

浅谈文件读写——C#


基于C#实现文件读写

文件读取

此方法凭借窗体台程序中的Richtextbox控件暂存文本中的数据,然后通过Richtextbox自带的读取功能按行读取。

private void 打开OToolStripMenuItem_Click(object sender, EventArgs e){richTextBox1.Clear();OpenFileDialog pdlg = new OpenFileDialog();pdlg.Filter = \"所有文件|*.*\";DialogResult rt = pdlg.ShowDialog();if (rt == DialogResult.OK){string filename = pdlg.FileName;richTextBox1.LoadFile(filename, RichTextBoxStreamType.PlainText);}}

字符串分割

  1. richTextBox1.Lines.Length ·····计算行数
  2. richTextBox1.Lines[ii] ····· 一行字符串是数组的一项
  3. .Trim() ·····实现去除字符串前后的空格
  4. string[] iarray = iline.Split(new char[] { ’ ’ }, StringSplitOptions.RemoveEmptyEntries);·····返回值不包含空格
  5. 可以配合正则表达式使用。
int row = richTextBox1.Lines.Length;int ii = 0;string find = \"\";for (ii = 0; ii < row; ii++){find = richTextBox1.Lines[ii];find = find.Trim();if (find == \"END OF HEADER\")break;}int i;for (i = ii+1; i < row; i++){string iline = richTextBox1.Lines[i];string[] iarray = iline.Split(new char[] { \' \' }, StringSplitOptions.RemoveEmptyEntries);int j = 0;for (j = 0; j < iarray.Length; j++){if (iarray[0] == \"2\" && iarray[1] == \"08\" && iarray[2] == \"5\" && iarray[3] == \"14\" && iarray[4] == \"2\")break;}if (j < iarray.Length)break;}double[,] all = new double[7, 4];string[] starray = new string[7]; int m = 0;for (int k = i+1; k < i+8; k++, m++){string iline = richTextBox1.Lines[k];starray[m] = iline;}string stallof = \"\";foreach (string strs in starray){stallof = stallof + strs;}Regex p = new Regex(@\"(-??\\d[.]\\d{12}[\'D\'][+-]\\d\\d)\");MatchCollection collection = p.Matches(stallof);double[] alls = new double[28];for (int n = 0; n < 25; n++)///{string[] temst = collection[n].Value.Split(\'D\');alls[n] = double.Parse(temst[0]) * Math.Pow(10, double.Parse(temst[1]));}

文件写入

1.格式化输出

richTextBox3.Text = \"---------------计算X Y Z数据显示--------------------\\r\\n\";foreach (XYZ yZ in xzyss){string sout = String.Format(\"{0,12:F6}   {1,12:F6}  {2,12:F6}\\r\\n\", yZ.X, yZ.Y, yZ.Z);richTextBox3.Text += sout;}

2.文件保存

SaveFileDialog pdlg = new SaveFileDialog();pdlg.Filter = \"文本文件|*.txt|所有文件|*.*\";DialogResult rt = pdlg.ShowDialog();if (rt == DialogResult.OK){string filename = pdlg.FileName;richTextBox3.SaveFile(filename, RichTextBoxStreamType.PlainText);}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 浅谈文件读写——C#