我想从字符串中获取数字,我做了。
我想将此char转换为数据库的任何interger,但会收到以下错误: ' /'中的服务器错误应用
输入字符串的格式不正确。
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.
代码:
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)
答案 0 :(得分:5)
您不需要转换字符串,您可以将其中的字符作为Char
值进行访问。您可以使用Char.IsDigit
检查数字:
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
答案 1 :(得分:2)
由于字符串中有多个数字,因此您需要单独解析每个数字。
For Each ch As Char In myChars
If Integer.TryParse(ch, iChar) Then
Exit For
End If
Next
答案 2 :(得分:0)
您可以使用LINQ获取第一个数字并获得没有数字的指示:
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