Error System.InvalidCastException: 'Conversion from string "" to type 'Integer' is not valid.' - vb.net

I'm trying to open a file that I already add to my TreeView control by clicking it twice, it should appears in a DataGridView control, when a I do it, it shows me the next error:
System.InvalidCastException: 'Conversion from string "Book1.csv" to type 'Integer' is not valid.'
At the Direccion variable, I'm not pretty sure, what it happening. Does any one could orient me? Please.
Public Sub TV_NodeMouseDoubleClick(ByVal sender As Object, ByVal e As
TreeNodeMouseClickEventArgs) Handles TV.NodeMouseDoubleClick
Dim NombreNodo As String = TV.SelectedNode.Text
Dim parseCSV As String
Dim tstSeq() As String
Dim Direccion As String = My.Computer.FileSystem.CurrentDirectory(NombreNodo)
'Dim x As String = Path.GetFullPath(NombreNodo)
'MessageBox.Show(Direccion)
tstSeqDataGrid.Rows.Clear()
Using FileSystem As FileStream = File.Open(Direccion, FileMode.Open, FileAccess.Read)
Dim TestReader As New System.IO.StreamReader(FileSystem)
Do While TestReader.Peek <> -1
parseCSV = TestReader.ReadLine()
tstSeq = parseCSV.Split(",")
tstSeqDataGrid.Rows.Add(tstSeq)
TstSequenceLoaded = True
Loop
TestReader.Close()
FileSystem.Close()
End Using
End Sub

I am assuming that the TreeView is loaded with file names and those files are located in the directory where the code is running. You can see the value of Direccion in the Immediate Window. Using Debug.Print instead of a message box saves you from the embarrassment of forgetting to remove the message box in the production code. The Debug.Print will just be removed.
I returned an array of lines in the file with ReadAllLines. Then loop through the lines as you did.
With Option Strict On (as it should be) you need to add the lower case c following "," so the compiler knows you intend it as a Char not a String.
Public Sub TV_NodeMouseDoubleClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TV.NodeMouseDoubleClick
Dim Direccion = My.Computer.FileSystem.CurrentDirectory & TV.SelectedNode.Text
Debug.Print(Direccion)
tstSeqDataGrid.Rows.Clear()
Dim lines = File.ReadAllLines(Direccion)
For Each line In lines
Dim tstSeq = line.Split(","c)
tstSeqDataGrid.Rows.Add(tstSeq)
Next
TstSequenceLoaded = True
End Sub

Related

VB.Net Search for text and replace with file content

This is a follow on question to a post I made. Append one file into another file
I need to search the master document for entities "&CH1.sgm" to "&CH33.sgm",
mark where they are in the master document and replace the entity call with the matching file "Chapter1.sgm" found in "fnFiles". I can change the file names and entities to anything if that will help.
My code copies the text of a file and appends it to the bottom of the master_document.sgm. But now I need it to be more intelligent. Search the Master document for entity markers, then replace that entity marker with that file contents match. The file number and entity number match up. e.g.(&CH1; and Bld1_Ch1.sgm)
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
Dim searchDir As String = txtSGMFile.Text 'Input field from form
Dim masterFile = "Bld1_Master_Document.sgm"
Dim existingFileMaster = Path.Combine(searchDir, masterFile)
'Read all lines of the Master Document
Dim strMasterDoc = File.ReadAllText(existingFileMaster) '// add each line as String Array.
'?search strMasterDoc for entities &Ch1.sgm
'?replace entity name "&Ch1.sgm" with content of file "Bld1_Ch1.sgm" this content if found below
'? do I use a book mark? Replace function?
'Get all the sgm files in the directory specified
Dim fndFiles = Directory.GetFiles(searchDir, "*.sgm")
'Set up the regular expression you will make as the condition for the file
Dim rx = New Regex(".*_Ch\d\.sgm")
Dim ch1 = New Regex(".*_Ch[1]\.sgm")
'Use path.combine for concatenatin directory together
'Loop through each file found by the REGEX
For Each fileNo In fndFiles
If rx.IsMatch(fileNo) Then
If ch1.IsMatch(fileNo) Then
Dim result = Path.GetFileName(fileNo)
'Use path.combine for concatenatin directory together
Dim fileToCopy = Path.Combine(searchDir, result)
'This is the file we want to copy into MasterBuild but at specific location.
'match &ch1.sgm inside strMasterDoc
Dim fileContent = File.ReadAllText(fileToCopy)
'Search master file for entity match then append all content of fileContent
File.AppendAllText(existingFileMaster, fileContent)
MessageBox.Show("File Copied")
End If
End If
Next
Close()
End Sub
If I understand correctly (big if), you want to replace the the text of the abbreviated chapter name in the master file with the contents of the file it refers to at the spot where the abbreviation is found.
I made a class to handle the details.
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
'Add a FolderBrowseDialog to your form designer
FolderBrowserDialog1.ShowDialog()
Dim searchDir As String = FolderBrowserDialog1.SelectedPath
Dim existingFileMaster = Path.Combine(searchDir, "Bld1_Master_Document.sgm")
Dim lstFileChanges = CreateList(searchDir)
'The following method does NOT return an array of lines
Dim strMasterDoc = File.ReadAllText(existingFileMaster)
For Each fc In lstFileChanges
strMasterDoc = strMasterDoc.Replace(fc.OldString, fc.NewString)
Next
File.WriteAllText(existingFileMaster, strMasterDoc)
End Sub
Private Function CreateList(selectedPath As String) As List(Of FileChanges)
Dim lstFC As New List(Of FileChanges)
For i = 1 To lstFC.Count
Dim fc As New FileChanges
fc.OldString = $"&CH{i}.sgm"
fc.FileName = $"Chapter{i}.sgm"
fc.NewString = File.ReadAllText(Path.Combine(selectedPath, fc.FileName))
lstFC.Add(fc)
Next
Return lstFC
End Function
Public Class FileChanges
Public Property OldString As String '&CH1.sgm
Public Property FileName As String 'Chapter1.sgm
Public Property NewString As String 'Contents of Chapter1.sgm, the string to insert
End Class
Testing .Replace
Dim s As String = "The quick brown fox jumped over the lazy dogs."
s = s.Replace("fox", "foxes")
MessageBox.Show(s)

Error when assigning return value of ReadAllLines to variable

I am currently struggling with this function in Visual Studio:
Private Sub dlsuc()
Dim file_ As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\v.txt"
Dim file As String = IO.File.ReadAllLines(file_)
End Sub
I can't get this to work, I get something like these error messages:
Error 1 Value of type '1-dimensional array of String' cannot be converted to 'String'.
What is the reason for this?
This is because File.ReadAllLines() returns an array of strings. You can read more about it here.
Instead, try it like this:
Private Sub dlsuc()
Dim file_ As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\v.txt"
Dim file As String() = IO.File.ReadAllLines(file_)
End Sub
Notice the () in the variable declaration.

Variable has already been used before and assigned a value

I' am making a bot for my assignment which uses proxy to browse websites. I have field called "Browse" which lets me browse for the proxy file and reads into an array and shows the total number of proxy from the counter. I' am stuck here in the following. The following are the code that am currently using. Please help
Variable proxyArray has already been used before and assigned a value. A null
reference exception could result at runtime.
Code
Private Sub browserProxy_Click(sender As Object, e As EventArgs) Handles browserProxy.Click
Dim myStream As Stream = Nothing
Dim selectedFile As String
Dim openFileDialog1 As New OpenFileDialog()
Dim proxyArray() As String
Dim totalProxy As Integer
openFileDialog1.InitialDirectory = "C:\"
openFileDialog1.Filter = "Text File (*.txt)|*.txt"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = False
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
selectedFile = String.Format(openFileDialog1.FileName)
Dim objreader As New System.IO.StreamReader(selectedFile)
i = 0
Do While Not objreader.EndOfStream
proxyArray(i) = objreader.ReadLine
i += 1
Loop
totalProxy = i
objreader.Close()
End If
End Sub
This pops up during runtime.
The compiler is right, you have declared the variable proxyArray but you never initialize it. This is an initialized array with 10 strings that are Nothing
:
Dim proxyArray(9) As String
But since the number of items is unknown you should use a List(Of String) anyway. It is resizable whereas an array has a fixed size.
Dim proxList As New List(Of String)
'...'
proxList.Add(objreader.ReadLine)
If you need an array you can use proxList.ToArray() at the end.
Either use a List(Of String), or ReDim Preserve proxyArray(i + 1) each time.

String Letter Converted on 0

I want to make a program (on VB) to Copy a especific Folder from an USB, but whatever that I Use (TextBox, ComboBox, ListBox), always the DriveR Letter (C: for test) is converted to a 0, so te program doesn't works. If I Use another Dim...As.., like Integer, I get the "An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll" Error
here is my Code:
Private Sub RespJ_Click(sender As Object, e As EventArgs) Handles RespJ.Click
Dim CarpetaI, CarpetaL, ID As String
Dim Letra As Integer
Letra = Val(combobox1.Text)
ID = Val(IDTB.Text)
CarpetaI = Letra + ":\WPSystem\AppData\" + ID
CarpetaL = "C:\RespaldoWP\WPSystem\AppData\" + ID
Label1.Text = CarpetaI
'My.Computer.FileSystem.CreateDirectory(CarpetaL)
'My.Computer.FileSystem.CopyDirectory(CarpetaI, CarpetaL, True)
End Sub
*The last 2 lines are commented because I want to test the Code (Using a label to see if the path is correct) before to make it copy/past on real/testing files
There are two problems here:
Your variable should be a String:
Dim Letra As String
Don't use the Val function to read the drive letter from the combo box:
Letra = combobox1.Text

Error In VB.Net code

I am getting the error "Format Exception was unhandled at "Do While objectReader.Peek <> -1
" and after. any help would be wonderful.
'Date: Class 03/20/2010
'Program Purpose: When code is executed data will be pulled from a text file
'that contains the named storms to find the average number of storms during the time
'period chosen by the user and to find the most active year. between the range of
'years 1990 and 2008
Option Strict On
Public Class frmHurricane
Private _intNumberOfHuricanes As Integer = 5
Public Shared _intSizeOfArray As Integer = 7
Public Shared _strHuricaneList(_intSizeOfArray) As String
Private _strID(_intSizeOfArray) As String
Private _decYears(_intSizeOfArray) As Decimal
Private _decFinal(_intSizeOfArray) As Decimal
Private _intNumber(_intSizeOfArray) As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'The frmHurricane load event reads the Hurricane text file and
'fill the combotBox object with the data.
'Initialize an instance of the StreamReader Object and declare variable page 675 on the book
Dim objectReader As IO.StreamReader
Dim strLocationAndNameOfFile As String = "C:\huricanes.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Please restart application when available"
'This is where we code the file if it exist.
If IO.File.Exists(strLocationAndNameOfFile) Then
objectReader = IO.File.OpenText(strLocationAndNameOfFile)
'Read the file line by line until the file is complete
Do While objectReader.Peek <> -1
**_strHuricaneList(intCount) = objectReader.ReadLine()
_strID(intCount) = objectReader.ReadLine()
_decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine())
_intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine())
intCount += 1**
Loop
objectReader.Close()
'With any luck the data will go to the Data Box
For intFill = 0 To (_strID.Length - 1)
Me.cboByYear.Items.Add(_strID(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Me.Close()
End If
End Sub
Put a break-point on these lines and step through your code:
_decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine())
_intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine())
Whatever is being returned by ReadLine isn't in the proper decimal or integer format when passed to the converters. You'll need to add some try/catch blocks around the do-while loop operations to handle it gracefully and make sure your data is formatted the way you expected since the wrong parts are being used in this scenario.
Also, each call to ReadLine is returning an entirely new line and the Peek check won't account for those. As long as you can trust your data that's fine.
Instead of using Convert.ToDecimal an Convert.ToInt32, try using Decimal.TryParse() and Int32.TryParse(). If they don't parse, you know your file isn't setup correctly. If they do parse, then you've loaded the value into a variable for your use.
EDIT:
Use it like this.
Dim myDecimal As Decimal
If Decimal.TryParse(objectReader.ReadLine(), myDecimal) Then
'your string successfully parsed. Use myDecimal however you want. It has the parsed value.
Else
'your string is not a decimal. Now that you know that, you can handle this situation here without having to catch an exception.
End If