将字符串转换为整数:格式无效

时间:2015-10-09 10:57:27

标签: .net vb.net string integer type-conversion

我正在处理一个应用程序,我正在从文本文件中读取一行到String。然后,我通过使用CInt(String)将该String转换为Integer。但是,我收到错误说

Conversion from  to type Integer is not valid

(我已将其翻译过来,因此错误输出可能不完全相同)。令我困惑的是,在“from”和“to”之间,有两个空格,就好像String没有名字一样。但是当我做“MsgBox(String)”时,它确实告诉我它的价值。 Integer.Parse()也无效。

这是我的代码:

Dim ulistreader As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader("tmp\user.list")
Dim userList As String = ulistreader.ReadLine
If userList = "-1" Then
    Exit Sub
End If
MsgBox(userList) 'Output is 0
Dim UListInt As Integer = Integer.Parse(userList) 'This is where I get the error. Tried CInt(userList), didn't work

直到今天,代码工作正常。我刚刚开始我几天前制作的.exe,现在它突然不起作用了。我有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试使用指定的值重现:

    Dim userList As String = "0"
    Dim UListInt As Integer

    If Not Integer.TryParse(userList, UListInt) Then
        'conversion failed
        Stop
    End If
    Debug.WriteLine(UListInt.ToString)

无法重现。所以尝试了这个并没有失败,因为换行是最后的空白。

    Dim userList As String = "0" & ControlChars.CrLf
    Dim UListInt As Integer

    If Not Integer.TryParse(userList, UListInt) Then
        'conversion failed
        For Each c As Char In userList
            Debug.WriteLine(AscW(c))
        Next
    End If
    Debug.WriteLine(UListInt.ToString)

最后这个失败

    Dim userList As String = "o" & ControlChars.CrLf
    Dim UListInt As Integer

    If Not Integer.TryParse(userList, UListInt) Then
        'conversion failed
        For Each c As Char In userList
            Debug.WriteLine(AscW(c))
        Next
    End If