+ -
当前位置:首页 → 问答吧 → 有关读取Txt文件的输入格式错误,求高人指点

有关读取Txt文件的输入格式错误,求高人指点

时间:2011-08-13

来源:互联网

本人碰到一个让我快崩溃的问题:

问题是这样的:从一个Txt文件(为三列数据)中读取数据,通过String的Split函数分割后用Arraylist存贮。这个问题本来问题不大:我是这这样做的:
 Dim Openfile As New System.Windows.Forms.OpenFileDialog
  Openfile.Title = "读取文件"
  Openfile.Filter = "All Files|*.*|Text Files|*.txt"
  If Openfile.ShowDialog() = DialogResult.OK Then
  Dim tempStreamReader As New System.IO.StreamReader(Openfile.FileName)
  Dim tempstr As String = tempStreamReader.ReadLine
  Dim tempcount As Int16 = 0
  Dim tempx, tempy, tempz As Double
  Dim Points As ArrayList =New ArrayList 
  Try
  While tempstr IsNot Nothing
  Dim tempstr1() As String = tempstr.Split(CChar(","))
  tempx = System.Double.Parse(tempstr1(0).ToString)
  tempy = System.Double.Parse(tempstr1(1).ToString)
  tempz = System.Double.Parse(tempstr1(2).ToString)
  'tempx = Convert.ToDouble(tempstr1(0).ToString)
  'tempy = Convert.ToDouble(tempstr1(1).ToString)
  'tempz = Convert.ToDouble(tempstr1(2).ToString)
  Points.Add(New SpatialPoint(tempx, tempy, tempz))
  tempstr = tempStreamReader.ReadLine()
  End While
  Catch e As Exception
  MessageBox.Show(e.ToString)
  End Try
  tempStreamReader.Close()
  'tempStreamReader = Nothing
  End If
  一个星期前,我将这段代码整合到一个模型中,当时运行一点问题没有。今天再运行时,发现一件怪事:系统总是报错说:“System.FormatException输入字符格式不对”。而且,我单独取出txt文件的一行做测试时,却发现运行正常:
————————————————————————
  Dim str As String = "34,45.5,67.8"
  Dim str1 As String() = str.Split(CChar(","))
  Dim k As Integer = str1.Length - 1
  Dim i As Integer = 0
  Dim inte As double
  For i = 0 To k
  'inte = Convert.ToDouble(str1(i))
  'inte = Convert.ToDouble(str1(i).ToString)
  'inte = CType(str1(i).ToString, Double)
  inte = System.Int16.Parse(str1(i).ToString)
  MsgBox(str1(i))
  Next
——————————————————————————————————————————
请问到底怎么回事?

作者: zhousmith2011   发布时间: 2011-08-13

[img=http://C:\Documents   and   Settings\All   Users\Documents\报错.jpeg][/img]

作者: zhousmith2011   发布时间: 2011-08-13

估计txt文件数据有问题,出错时你查看一下tempstr的值是什么

作者: c_cyd2008   发布时间: 2011-08-13

我检查了txt文件里面里面包含的逗号是半角的。我发现了问题:
While tempstr IsNot Nothing
  Dim tempstr1() As String = tempstr.Split(CChar(","))
  tempx = System.Double.Parse(tempstr1(0).ToString)
  tempy = System.Double.Parse(tempstr1(1).ToString)
  tempz = System.Double.Parse(tempstr1(2).ToString)
  'tempx = Convert.ToDouble(tempstr1(0).ToString)
  'tempy = Convert.ToDouble(tempstr1(1).ToString)
  'tempz = Convert.ToDouble(tempstr1(2).ToString)
  MsgBox(tempz )(能够显示tempz,但是当读完整个txt文件到空行时,就会出现输入格式错误的问题)
  Points.Add(New SpatialPoint(tempx, tempy, tempz))
  tempstr = tempStreamReader.ReadLine()
  End While

是不是,我写的代码中前后两个tempStreamReader.ReadLine位置摆错了?

作者: zhousmith2011   发布时间: 2011-08-13

热门下载

更多