how to get value from spilt function in to string array - vb.net

i want to use split function for splitting string into two parts.The question is how can i save the first part and second part into two different string array for further use?
The text i'm going to process is Name,filepath
Dim clientArr() as string
Dim FileArr() as string
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
ClientArr = DataArr(0)
FileArr = DataArr(1)
loop
The error says that string cannot be convented into 1 D array
Thank you

It is the 21st Century and along with flying cars and robot dogs we have a easy way to keep 2 large sets of related data together in a single container, but able to be referenced individually:
Class myFileParts
public Property FileName As String
public Property FilePath As String
Public Sub New(fName as string, fPath as String)
FileName = fName
FilePath = fPath
End Sub
End Class
' a container to hold lots of these
Friend myFiles As New List(Of myFileParts)
' filling it up:
Dim TempLine As String
Dim myF As myFileParts
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
' create a file item
f = New myFileParts(DataArr(0),DataArr(1))
' add to container
myFiles.Add(f)
loop
to use one: (N is the index of the desired file info):
Dim thisFile As string = MyFiles(N).FileName
Dim thisPath As string = MyFiles(N).FilePath
to print them all:
For each f As myFileParts in myFiles
Console.WriteLine(String.Format("Path = {0}; Name = {1}",
f.FilePath, f.FileName)
Next f

The problem is that you declare ClientArr and FileArr as string arrays, which is what you want, but then you try to assign them a string value. DataArr(0) is a string value. You need to put that vcalue into one of the array elements in ClientArr. E.g. CleintArr(5) = DataArr(0).
If you knew the exact number of line in the file before the loop then you could declare the array size for CleintArr and FileArr. Then you would use an index that gets increments in the loop to set the proper array element.
But here is a better approach that will work without knowing the size of the file beforehand. This uses string collections to accumulate the clients and files, and then it converts them to an array once the file has been read.
Dim clientArr() As String
Dim FileArr() As String
Dim ClientList As New List(Of String)
Dim FileList As New List(Of String)
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
ClientList.Add(DataArr(0))
FileList.Add(DataArr(1))
Loop
clientArr = ClientLIst.ToArray()
FileArr = FileList.ToArray()

Do you know how many lines are in the file before you start? If not, you could do something like this using the List class:
Dim clientPart As List(Of String) = New List(Of String)()
Dim filePart As List(Of String) = New List(Of String)()
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
clientPart.Add(DataArr(0))
filePart.Add(DataArr(1))
Loop
Dim clientPartStringArray As String() = clientPart.ToArray() 'If you really want an array
If you do, then you need to assign each split to an element of your clientArr and fileArr like:
Dim numLinesInFile As Integer 'If you know this value
Dim curIndex As Integer = 0
Dim clientArray(numLinesInFile) As String
Dim fileArray(numLinesInFile) As String
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
clientArray(curIndex) = DataArr(0)
fileArray(curIndex) = DataArr(1)
curIndex = curIndex + 1
Loop
Note the differences in your code in terms of:
We declare the arrays clientArray and fileArray with a specific size (you'll need to know this in advance - if you don't/can't know this consider using a collection like a List as previously alluded to)
On each iteration we assign the strings you get from the Split into a specific index of the array denoted by curIndex
We have to increment curIndex by 1 each time so that we write to empty slots in clientArray and fileArray...otherwise you'd just write to the same index (0) each time

Related

How can I reasd text from text file while there are multiple line and generate a string so I can use it as sqlconnection string?

I have a config file which contain multiple lines.
DataBaseType =1
ServerName=LAPTOP-XXXX
Database=mydatabase
Connection Timeout=3000
User ID=sa
Password=sasa
ServerIp=xxxx:8083
ServiceType=http://
Backup Driver=D:\
Backup Folder=SWBACKUP
Database Restore=D:\
Now I want to generate a string which will be a sqlconnection string by reading,splitting and joining texts. it should be
"Data Source=LAPTOP-XXXX;Initial Catalog=mydatabase;User ID=sa;Password=sasa"
I am able to read text using streamreader , but I am not able to split and join those texts.
You can create a method that converts your config file to a Dictionary(Of String, String) and then get the values as needed.
Take a look at this example:
Private Function ReadConfigFile(path As String) As Dictionary(Of String, String)
If (String.IsNullOrWhiteSpace(path)) Then
Throw New ArgumentNullException("path")
End If
If (Not IO.File.Exists(path)) Then
Throw New ArgumentException("The file does not exist.")
End If
Dim config = New Dictionary(Of String, String)
Dim lines = IO.File.ReadAllLines(path)
For Each line In lines
Dim separator = line.IndexOf("=")
If (separator < 0 OrElse separator = line.Length - 1) Then
Throw New Exception("The following line is not in a valid format: " & line)
End If
Dim key = line.Substring(0, separator)
Dim value = line.Substring(separator + 1)
config.Add(key, value)
Next
Return config
End Function
Example: Live Demo
What this Function does is:
Make sure that a path was given
Make sure that the file exists as the given path
Loop over each line
Make sure that the line is in the correct format (key=value)
Append the Key/Value to the Dictionary
you can use readline method, then make something as follow for database line:
Dim reader As New StreamReader(filetoimport.Txt, Encoding.Default)
Dim strLine As String
Do
' Use ReadLine to read from your file line by line
strLine = reader.ReadLine
Dim retString As String
'to get the string from position 0 length 8
retString = strLine .Substring(0, 8)
'check if match
if retString ="Database" Then
Dim valueString As String
valueString = strLine .Substring(9, strLine.length)
...
Loop Until strLine Is Nothing

VB.NET: GetFiles() in Specific Directory

Currently the line of code looks like this:
Dim files() As String = System.IO.Directory.GetFiles(path, filehead & ".*.*.fsi")
Dim seqfsi() As Integer
ReDim seqfsi(files.GetUpperBound(0))
Dim args() As String
Dim file As String = ""
For Each file In files
args = Split(file, ".")
If args.Length = 4 Then
seqfsi(System.Array.IndexOf(files, file)) = CInt(args(args.GetUpperBound(0) - 1))
End If
The problem is, sometimes, in my case, the path looks something like:
C:\Users\c.brummett\Downloads
and the split causes a split in the username. How can I avoid this problem but still split by periods? I'm sorry I don't how to make this more relatable.
My idea was to use a DirectoryInfo and do something like:
Dim di As DirectoryInfo
di = New DirectoryInfo(path)
Dim files() As String = di.GetFiles(filehead & ".*.*.fsi")
Edit: The problem with this second bit of code, is that it returns the error
Value of type '1-dimensional array of System.IO.FileInfo' cannot be converted to '1-> dimensional array of String' because 'System.IO.FileInfo' is not derived from 'String'.`
You can forget about getting an array of file names (you don't need that anyway) and iterate on the array of FileInfo:
Dim files() As FileInfo = New DirectoryInfo(path).GetFiles(filehead & ".*.*.fsi")
Dim seqfsi() As Integer
ReDim seqfsi(files.GetUpperBound(0))
Dim args() As String
For Each file As FileInfo In files
args = Split(file.Name, ".")
If args.Length = 4 Then
seqfsi(System.Array.IndexOf(files, file)) = CInt(args(args.GetUpperBound(0) - 1))
End If
Note AllDirectories and change in the line doing the splitting. I didn't look at your array structure stuff.
Dim files() As String = System.IO.Directory.GetFiles("C:\temp", "*.doc", IO.SearchOption.AllDirectories)
Dim seqfsi() As Integer
ReDim seqfsi(files.GetUpperBound(0))
Dim args() As String
Dim file As String = ""
For Each file In files
args = file.Substring(file.LastIndexOf("\") + 1).Split(".")
If args.Length = 4 Then
seqfsi(System.Array.IndexOf(files, file)) = CInt(args(args.GetUpperBound(0) - 1))
End If
Next file

Splitting file into parts for dictionary use

I have an uploaded file, displaying
Han 33.3
Han 5.66
Han 8.3
Chewbacca 99.4
Chewbacca 100.3
Chewbacca 98.1
I need to make an average for each han and Chewbacca using a dictionary, but first I have to split the list in order to do that. How do I split them for this purpose.
I'm making the assumption that the whitespace between the name and quantity is a single space. I'm also calling your values "scores" and Han and Chewbacca "players" for my example solution. The result splits the line into individual key-value pairs; each key represents the list of values found; it:
Imports System.IO
Dim pathToYourFile As String = "Path to your file with file name"
Dim f As StreamReader = File.OpenText(pathToYourFile)
Dim fileText As String = f.ReadToEnd
f.Close()
Dim singleSpace As String = " " 'single space between quotes
Dim playerScores As New SortedDictionary(Of String, List(Of Double))
Dim lines() As String = fileText.Split(vbCrLf.ToCharArray())
For i As Integer = 0 To lines.Length - 1
Dim scoreLine() As String = lines(i).Split(" ".ToCharArray())
Dim playerName As String = scoreLine(0)
Dim score As Double = Double.Parse(scoreLine(1))
If playerScores.ContainsKey(playerName) Then
playerScores(playerName).Add(score)
Else
Dim list As New List(Of Double)
list.Add(score)
playerScores.Add(playerName, list)
End If
Next i
Try this:
Public Class DataClass
Public Property Name() As String
Public Property Value() As Decimal
End Class
' ...
Public Shared Function GetAverageDict(lines As IEnumerable(Of String)) _
As Dictionary(Of String, Decimal)
Dim lst As New List(Of DataClass)()
For Each line As String In lines
Dim lastSpaceIndex = line.LastIndexOf(" ")
If (lastSpaceIndex >= 0) Then
Dim name = line.Substring(0, lastSpaceIndex).Trim()
Dim value = Decimal.Parse(line.Substring(lastSpaceIndex + 1), _
System.Globalization.CultureInfo.InvariantCulture)
lst.Add(New DataClass() With { .Name = name, .Value = value })
End If
Next
Dim averages = From g In From x In lst _
Group x By key = x.Name _
Select New With { .Name = key, _
.Average = Group.Average(Function(y) y.Value) }
Return averages.ToDictionary(Function(x) x.Name, Function(y) y.Average)
End Function
The function first gets the parts from each line. It assumes that the last space is the separator between the parts. This way, the name can also contain space characters.
The data is collected in a list that is afterwards grouped by the name. By calling ToDictionary the result of the grouping operation is converted in a dictionary.
Call the function like this:
Dim dict = GetAverageDict(System.IO.File.GetLines(filePath))

Splitting a CSV Visual basic

I have a string like
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
in a file
in two separate lines. I am reading it from the textbox. I have to output ab563372363_C/R and ab563372356_C/R in a text box. I am trying to use the split function for that but its not working..
Dim splitString as Array
results = "test.txt"
Dim FileText As String = IO.File.ReadAllText(results) 'reads the above contents from file
splitString = Split(FileText, ",", 14)
TextBox2.text = splitString(1) & splitString(13)
for the above code, it just prints the whole thing.. What's wrong?
Try this
Private Function GetRequiredText() As List(Of String)
Dim requiredStringList As New List(Of String)
Dim file = "test.txt"
If FileIO.FileSystem.FileExists(file) Then
Dim reader As System.IO.StreamReader = System.IO.File.OpenText(file)
Dim line As String = reader.ReadLine()
While line IsNot Nothing
requiredStringList.Add(line.Split(",")(1))
line = reader.ReadLine()
End While
reader.Close()
reader.Dispose()
End If
Return requiredStringList
End Function
This will read the file line by line and add the item you require to a list of strings which will be returned by the function.
Returning a List(Of String) may be overkill, but it's quite simple to illustrate and to work with.
You can then iterate through the list and do what you need with the contents of the list.
Comments welcome!!
Also this might work...
Dim query = From lines In System.IO.File.ReadAllLines(file) _
Select lines.Split(",")(1)
this will return an IEnumerable(Of String)
Enjoy
First
Since you are reading the whole text, your FileText would be ending like this:
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132,460
\r\n
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
So when you are referencing to your splitStringwith those indexes (1, 13) your result might probably be wrong.
Second
Try to specify what kind of type your array is, Dim splitString as Array should be Dim splitString As String()
Third
Make your code more readable/maintainable and easy to edit (not only for you, but others)
The Code
Private const FirstIndex = 1
Private const SecondIndex = 12
Sub Main
Dim myDelimiter As Char
Dim myString As String
Dim mySplit As String()
Dim myResult1 As String
Dim myResult2 As String
myDelimiter = ","
myString += "Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460"
myString += "Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455"
mySplit = myString.Split(myDelimiter)
myResult1 = mySplit(FirstIndex)
myResult2 = mySplit(SecondIndex)
Console.WriteLine(myResult1)
Console.WriteLine(myResult2)
End Sub

String Array Thing!

Right - to start with, I'm entering unfamiliar areas with this - so please be kind!
I have a script that looks a little something like this:
Private Function checkString(ByVal strIn As String) As String
Dim astrWords As String() = New String() {"bak", "log", "dfd"}
Dim strOut As String = ""
Dim strWord As String
For Each strWord In astrWords
If strIn.ToLower.IndexOf(strWord.ToLower, 0) >= 0 Then
strOut = strWord.ToLower
Exit For
End If
Next
Return strOut
End Function
It's function is to check the input string and see if any of those 'astrWords' are in there and then return the value.
So I wrote a bit of code to dynamically create those words that goes something like this:
Dim extensionArray As String = ""
Dim count As Integer = 0
For Each item In lstExtentions.Items
If count = 0 Then
extensionArray = extensionArray & """." & item & """"
Else
extensionArray = extensionArray & ", ""." & item & """"
End If
count = count + 1
Next
My.Settings.extensionArray = extensionArray
My.Settings.Save()
Obviously - it's creating that same array using list items. The output of that code is exactly the same as if I hard coded it - but when I change the first bit of code to:
Dim astrWords As String() = New String() {My.Settings.extensionArray}
instead of:
Dim astrWords As String() = New String() {"bak", "log", "dfd"}
It starts looking for the whole statement instead of looping through each individual one?
I think it has something to do with having brackets on the end of the word string - but I'm lost!
Any help appreciated :)
When you use the string from the settings in the literal array, it's just as if you used a single strings containing the delimited strings:
Dim astrWords As String() = New String() {"""bak"", ""log"", ""dfd"""}
What you probably want to do is to put a comma separated string like "bak,log,dfd" in the settings, then you can split it to get it as an array:
Dim astrWords As String() = My.Settings.extensionArray.Split(","C)
You need to set extensionArray up as a string array instead of simply a string.
Note that
Dim something as String
... defines a single string, but
Dim somethingElse as String()
... defines a whole array of strings.
I think with your code, you need something like:
Dim extensionArray As String() = new String(lstExtensions.Items)
Dim count As Integer = 0
For Each item In lstExtentions.Items
extensionArray(count) = item
count = count + 1
Next
My.Settings.extensionArray = extensionArray
My.Settings.Save()
Then at the start of checkString you need something like
Private Function checkString(ByVal strIn As String) As String
Dim astrWords As String() = My.Settings.extensionArray
...
There also might be an even easier way to turn lstExtentions.Items into an Array if Items has a 'ToArray()' method, but I'm not sure what Type you are using there...
What you've done is created a single string containing all 3 words. You need to create an array of strings.
New String() {"bak", "log", "dfd"}
means create a new array of strings containing the 3 strings values "bak", "log" and "dfd".
New String() {My.Settings.extensionArray}
means create a new array of strings containing just one value which is the contents of extensionArray. (Which you have set to ""bak", "log", "dfd""). Note this is one string, not an array of strings. You can't just create 1 string with commas in it, you need to create an array of strings.
If you want to create your array dynamically, you need to define it like this:
Dim astrWords As String() = New String(3)
This creates an array with 3 empty spaces.
You can then assign a string to each space by doing this:
astrWords(0) = "bak"
astrWords(1) = "log"
astrWords(2) = "dfd"
You could do that bit in a for loop:
Dim count As Integer = 0
For Each item In lstExtentions.Items
astrWords(count) = item
count = count + 1
Next
Alternatively, you could look at using a generic collection. That way you could use the Add() method to add multiple strings to it
I think you want your extensionArray to be of type String() and not String. When you are trying to initialize the new array, the initializer doesn't know to parse out multiple values. It just sees your single string.