indofraiser
indofraiser

Reputation: 1024

Char to Integer

I wanted to get the numerical numbers from a string, which I did.

I want to convert this char to any interger for the database but get the following error: Server Error in '/' Application.

Input string was not in a correct format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.FormatException: Input string was not in a correct format.

Code:

For Each File As FileInfo In New DirectoryInfo(("C:\Folder")).GetFiles("*.aspx", SearchOption.AllDirectories)
    vFileName = File.FullName
                    Dim myChars() As Char = vFileName.ToCharArray()
                    Dim iChar As Integer = Convert.ToInt32(myChars)
                    iChar = Mid(1, 1, iChar)

Upvotes: 0

Views: 111

Answers (3)

Andrew Morton
Andrew Morton

Reputation: 25023

You can use LINQ to get the first digit and get an indication of there being no digit:

Option Infer On

Imports System.IO

Module Module1

    Sub Main()
        Dim srcDir = "D:\inetpub\wwwroot" ' sample data

        ' Use Directory.EnumerateFiles if you want to get them incrementally, e.g.
        ' showing the list of files using AJAX.

        For Each f In Directory.GetFiles(srcDir, "*.aspx", SearchOption.AllDirectories)

            Dim num = Path.GetFileNameWithoutExtension(f).FirstOrDefault(Function(c) Char.IsDigit(c))

            If num <> Chr(0) Then
                Console.WriteLine("First digit is " & num)
            Else
                Console.WriteLine("No digit.")
            End If

        Next

        Console.ReadLine()

    End Sub

End Module

Upvotes: 0

Guffa
Guffa

Reputation: 700342

You don't need to convert the string, you can access the characters in it as Char values. You can use the Char.IsDigit to check for digits:

vFileName = File.FullName
Dim iChar As Integer = -1
For Each ch As Char In vFileName
  If Char.IsDigit(ch) Then
    iChar = Int32.Parse(ch)
    Exit For
  End If
Next

Upvotes: 5

Whitey
Whitey

Reputation: 431

Since there are multiple numbers in the string, you are going to need to parse each one individually.

For Each ch As Char In myChars
    If Integer.TryParse(ch, iChar) Then
        Exit For
    End If
Next

Upvotes: 2

Related Questions