For Each Value to array vb.net - vb.net

I need to extract a value from a process array to myArray:
File: MyClass.vb
Public Function getTheRunningProcess()
Dim MyArray As Array
For Each prso In Process.GetProcesses(System.Environment.MachineName)
'This is the value i want to extract and put it in a Array
MyArray() = prso.ProcessName.ToString
Next
'Now i need to return the MyArray so i can access its value from anywhere
Return MyArray
End Function
So i can access this value from anywhere like so:
File: Form1.vb
For Each MyValue As TheValueFromFunction_getTheRunningProcess()
Listbox.item.addItem(MyValue)
Next
Now you might be thinking i can directly use the process in the File: Form1.vb but here is the situation, i have to use this function over and over again in different form as the application demands it has to be.
So if this is possible then how?
Or if there is any other way to do this?
Please show me the right path.
Thanks in advance :)

Public Function getTheRunningProcess() As Generic.List(Of String)
Dim processList As New Generic.List(Of String)
For Each prso In Process.GetProcesses(System.Environment.MachineName)
processList.Add(prso.ProcessName.ToString)
Next
Return processList
End Function
You could try doing it with Lists... And then
Dim myProccessList = getTheRunningProcess()
For Each p In myProccessList
'Do something with p
Next
Hope it helps

Related

VB.net Apply function to items in a list

I have a list of string containing full file paths and I'd like to apply a function to each path in that list and get the result in the same or a new list.
Dim Remove As New List(Of String)
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Assemblies\045-0201.iam")
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Parts\212-D017.ipt")
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Parts\211-W01.iam")
Function FileName(spth As String) As String
'Returns filename with extension from full path
Return System.IO.Path.GetFileName(spth)
End Function
The end result I'd like is for the list Remove to contain the following. I know I could use a loop to do this but I've been learning about lambda expressions lately and feel there should be a simple solution to this.
{"045-0201.iam", "212-D017.ipt", "211-W01.iam"}
Try this
Dim Remove As New List(Of String)
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Assemblies\045-0201.iam")
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Parts\212-D017.ipt")
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Parts\211-W01.iam")
Remove = Remove.Select(Function(s)
Return IO.Path.GetFileName(s)
End Function).ToList
Calling Select and ToList on the existing List is most likely fine and what most people would do. It's worth being aware, though, that that will not modify the existing collection but rather return a new one. If you only have the one reference to that list then that's not a big deal but other references to the existing list will not see the change, e.g.
Dim fileNames As New List(Of String) From {"C:\Folder\File1.ext",
"C:\Folder\File2.ext",
"C:\Folder\File3.ext"}
Dim temp = fileNames
fileNames = fileNames.Select(Function(s) Path.GetFileName(s)).ToList()
For Each fileName In fileNames
Console.WriteLine(fileName)
Next
For Each fileName In temp
Console.WriteLine(fileName)
Next
If you run that then you'll see that the first loop displays just the files names but the second loop displays the full paths, because it still refers to the original list.
If that's a problem, there is another way to do this without an explicit loop:
Dim fileNames As New List(Of String) From {"C:\Folder\File1.ext",
"C:\Folder\File2.ext",
"C:\Folder\File3.ext"}
Dim temp = fileNames
Array.ForEach(Enumerable.Range(0, fileNames.Count).ToArray(),
Sub(i) fileNames(i) = Path.GetFileName(fileNames(i)))
For Each fileName In fileNames
Console.WriteLine(fileName)
Next
For Each fileName In temp
Console.WriteLine(fileName)
Next
If you run that then you'll see that both loops display just the file names because there's only one list.
That said, if the first code posed a problem because of multiple references to the list, I'd just use a loop.
I know you stated that you'd want something other than a loop, but there really is no needfor anything fancy here. By the way, writing Remove.Add sounds like a riddle.
Sub Main()
Dim Remove As New List(Of String)
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Assemblies\045-0201.iam")
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Parts\212-D017.ipt")
Remove.Add("C:\_Vault\Designs\Jobs\Customer\Job23\Parts\211-W01.iam")
Console.WriteLine("Before execution")
For Each s As String In Remove
Console.WriteLine(s)
Next
For i As Integer = 0 To Remove.Count - 1
Remove(i) = MyFunction(Remove(i))
Next
Console.WriteLine("After execution")
For Each s As String In Remove
Console.WriteLine(s)
Next
Console.ReadLine()
End Sub
Private Function MyFunction(path As String) As String
Return IO.Path.GetFileName(path)
End Function
This outputs:

How to search a folder with its subfolders and save the results to an array VB.NET

I am trying to execute a search on a folder and get an array of every result back. I found this code but it doesn't go into subfolders:
Dim Results As New List(Of String)
For Each strFileName As String In IO.Directory.GetFiles("pathToSearch")
If strFileName.Contains("searchTerm") Then
Results.Add(strFileName)
End If
Next
How can I do exactly this, but also look into the subfolders?
I'm not very knowledgeable about the search options in VB.NET yet, so I apologize in advance if this seems stupid. I have tried searching online but haven't found anything. I can't have a single string, it needs to be an array (this needs to be interpreted by the machine later in the program)
Thanks for any help
No recursion required. There is already an overload for this. You just need to call it with appropriate search option.
e.g. To list all txt files in the directory as well as the subdirectories you can do:
Dim foundFiles() As String = System.IO.Directory.GetFiles("path/to/dir", "*.txt", System.IO.SearchOption.AllDirectories)
In order to get the subfolders you might try some recursive function
Unless there's a file system search API with which I'm unfamiliar, this is going to involve a recursive method to perform the searching into sub-directories.
Helpfully, Microsoft even has a complete example of something very similar available. In VB it might look something like this (my VB is very rusty and this is free-hand code, by the way...):
Function FindFiles(ByVal dir As String, ByVal searchTerm As String) As List(Of String)
Dim Results As New List(Of String)
' search files in this directory
For Each strFileName As String In IO.Directory.GetFiles(dir)
If strFileName.Contains(searchTerm) Then
Results.Add(strFileName)
End If
Next
' recurse into child directories
For Each strDirectoryName As String In IO.Directory.GetDirectories(dir)
Results = Results.AddRange(FindFiles(strDirectoryName, searchTerm)
Next
Return Results
End Function
Make a recursive function that keeps calling itself until all subdirectories are checked:
Private Function GetAllFileNamesFromDirectory(ByVal strPath As String, ByVal strSearchTerm As String) As List(Of String)
Dim lstFileNames As New List(Of String)
Dim lstSubDirectories As List(Of String) = IO.Directory.GetDirectories(strPath).ToList()
Dim lstFilesToAdd As List(Of String) = IO.Directory.GetFiles(strPath).ToList()
For Each strFileToAdd As String In lstFilesToAdd
If strFileToAdd.Contains(strSearchTerm) Then
'Additional logic would be required to filter out the directory name.
lstFileNames.Add(strFileToAdd)
End If
Next
If lstSubDirectories.Count > 0 Then
lstSubDirectories.ForEach(Sub(strDirectoryPath As String)
Dim lstSubDirectoryFilesToAdd As List(Of String) = GetAllFileNamesFromDirectory(strDirectoryPath, strSearchTerm)
If lstSubDirectoryFilesToAdd.Count > 0 Then
lstFileNames.AddRange(lstSubDirectoryFilesToAdd)
End If
End Sub)
End If
Return lstFileNames
End Function

Variable in Array Variable

if i generate a label dynamically i can change the text as followed, variable is a string:
Form.Controls(variable).text = "test"
I now have a sub that will create some and will get some information out of arrays. I have a lot of them. I only want the function for tat specific array. I do not want a case or if. Thats why i was wondering if i can use a variable in the array variable. Sounds strange, here is what i mean:
Public TestArray() as String
Public Sub BuildStructure(ByVal Shelf As String)
Dim XMax as Integer
XMax = TestArray.GetLength(1)
End Sub
But instead of TestArray beeing hardcoded i want it to be replaced with Shelf. So whatever gets send into the sub will change the array that i'm using.
Is that possible some how or is the way totally wrong?
Thanks
You can use an arraylist object that you can easily add and remove items from at runtime. Here's the MSDN page: http://msdn.microsoft.com/en-us/library/7x4b0a97.aspx
Public TestArray As New ArrayList
Public Sub BuildStructure(ByVal Shelf As String)
TestArray.Add(Shelf)
End Sub
If you need an array, you can always call the .ToArray method on the ArrayList

VB.NET - Load a List of Values from a Text File

I Have a text file that is like the following:
[group1]
value1
value2
value3
[group2]
value1
value2
[group3]
value3
value 4
etc
What I want to be able to do, is load the values into an array (or list?) based on a passed in group value. eg. If i pass in "group2", then it would return a list of "value1" and "value2".
Also these values don't change that often (maybe every 6 months or so), so is there a better way to store them instead of a plain old text file so that it makes it faster to load etc?
Thanks for your help.
Leddo
This is a home work question?
Use the StreamReader class to read the file (you will need to probably use .EndOfStream and ReadLine()) and use the String class for the string manipulation (probably .StartsWith(), .Substring() and .Split().
As for the better way to store them "IT DEPENDS". How many groups will you have, how many values will there be, how often is the data accessed, etc. It's possible that the original wording of the question will give us a better clue about what they were after hear.
Addition:
So, assuming this program/service is up and running all day, and that the file isn't very large, then you probably want to read the file just once into a Dictionary(of String, List(of String)). The ContainsKey method of this will determine if a group exists.
Function GetValueSet(ByVal filename As String) As Dictionary(Of String, List(Of String))
Dim valueSet = New Dictionary(Of String, List(Of String))()
Dim lines = System.IO.File.ReadAllLines(filename)
Dim header As String
Dim values As List(Of String) = Nothing
For Each line As String In lines
If line.StartsWith("[") Then
If Not values Is Nothing Then
valueSet.add(header, values)
End If
header = GetHeader(line)
values = New List(Of String)()
ElseIf Not values Is Nothing Then
Dim value As String = line.Trim()
If value <> "" Then
values.Add(value)
End If
End If
Next
If Not values Is Nothing Then
valueSet.add(header, values)
End If
Return valueSet
End Function
Function GetHeader(ByVal line As String)
Dim index As Integer = line.IndexOf("]")
Return line.Substring(1, index - 1)
End Function
Addition:
Now if your running a multi-threaded solution (that includes all ASP.Net solutions) then you either want to make sure you do this at the application start up (for ASP.Net that's in Global.asax, I think it's ApplicationStart or OnStart or something), or you will need locking. WinForms and Services are by default not multi-threaded.
Also, if the file changes you need to restart the app/service/web-site or you will need to add a file watcher to reload the data (and then multi-threading will need locking because this is not longer confined to application startup).
ok, here is what I edned up coding:
Public Function FillFromFile(ByVal vFileName As String, ByVal vGroupName As String) As List(Of String)
' open the file
' read the entire file into memory
' find the starting group name
Dim blnFoundHeading As Boolean = False
Dim lstValues As New List(Of String)
Dim lines() As String = IO.File.ReadAllLines(vFileName)
For Each line As String In lines
If line.ToLower.Contains("[" & vGroupName.ToLower & "]") Then
' found the heading, now start loading the lines into the list until the next heading
blnFoundHeading = True
ElseIf line.Contains("[") Then
If blnFoundHeading Then
' we are at the end so exit the loop
Exit For
Else
' its another group so keep going
End If
Else
If blnFoundHeading And line.Trim.Length > 0 Then
lstValues.Add(line.Trim)
End If
End If
Next
Return lstValues
End Function
Regarding a possible better way to store the data: you might find XML useful. It is ridiculously easy to read XML data into a DataTable object.
Example:
Dim dtTest As New System.Data.DataTable
dtTest.ReadXml("YourFilePathNameGoesHere.xml")

What is the best way to clear an array of strings?

What is the best way to clear an array of strings?
Wrong way:
myArray = Nothing
Only sets the variable pointing to the array to nothing, but doesn't actually clear the array. Any other variables pointing to the same array will still hold the value. Therefore it is necessary to clear out the array.
Correct Way
Array.Clear(myArray,0,myArray.Length)
And of course there's the VB way using the Erase keyword:
Dim arr() as String = {"a","b","c"}
Erase arr
Depending what you want:
Assign Nothing (null)
Assign a new (empty) array
Array.Clear
Last is likely to be slowest, but only option if you don't want a new array.
If you're needing to do things like clear, you probably want a collection like List(Of String) rather than an array.
redim arr(1,1,1,1)
and then
redim (z,x,y,v) to your dimensions
Here's a simple call that I use to clear the contents of a string array:
Public Sub ClearArray(ByRef StrArray As String())
For iK As Int16 = 0 To StrArray.Length - 1
StrArray(iK) = ""
Next
End Sub
Then just call it with:
ClearArray(myLocalArray)
If you need to reinitialize with empty strings or other values not equal to Nothing/Null, you may get further using an extension method:
Option Strict On : Option Explicit On : Option Infer On
...
Public Delegate Sub ArrayForAllDelegate(Of T)(ByRef message As T)
<Extension>
Public Function ForAll(Of T)(ByRef self As T(), f As ArrayForAllDelegate(Of T)) As T()
Dim i = 0
While i < self.Length
f(self(i))
i += 1
End While
Return self
End Function
Then your initialization code:
Dim a = New String(3 - 1) {"a", "b", "c"}
...
a.ForAll(Sub(ByRef el) el = "") 'reinitialize the array with actual empty strings
I use this code:
Redim myarray(-1)