VB.Net Cant create "new line" "string" - vb.net

I am in need of assistance... i am trying to create a textfile with links in it. the code i have..
dim domain as string = "http://www.mywebsite/"
dim name as string = "username"
Dim link As String = New String("domain" & "name")
TextBox1.AppendText(link & Environment.NewLine)
Msgbox(textBox1.lines(0))
The problem is that MsgBox only shows up as "http://www.mywebsite/". the textbox does show "http://www.mywebsite/username" but when copied to text document it is:
Line0: http://www.mywebsite/
Line1:username
any ideas... tried using
Dim link As String = String.Join(domain & name) but that doesnt work nor does
Dim link As String = new String.Join(domain & name)
i need
Msgbox(textBox1.lines(0)) to display "http://www.mywebsite/username" not one or the other.

That was quick got a message saying to use. Dim link As String = String.Concat(domain & name)

i think you should move to StringBuilder first import Imports System.Text
'create a string with multiple lines
Dim a As New StringBuilder
a.AppendLine("hi")
a.AppendLine("there")
a.AppendLine("this")
a.AppendLine("is")
a.AppendLine("a")
a.AppendLine("test")
'read will makes read line by line
Dim read As String() = a.ToString.Split(vbNewLine)
'count has number of lines
Dim count As Integer = a.ToString().Split(vbNewLine).Length - 1
'lines will be added to combobox one by one
For i As Integer = 0 To count - 1
ComboBox1.Items.Add(read(i))
Next
you just should edit it to suits your needs i didnt understand what you needed exactly

Related

Listview - add File type & Last modified Subitems

I'm trying to add "file type" and "last modified" to my Listview when adding items in It same as in Explorer, but I don't find what property should be assigned to SubItem. Here is my code:
For Each MyFile As IO.FileInfo In ItemDirectory.GetFiles
Dim lvi As New ListViewItem
lvi.Tag = mFile.FullName
lvi.Text = mFile.Name
lvi.ImageKey = CacheShellIcon(mFile.FullName)
Listview1.Items.Add(lvi)
lvi.SubItems.Add("File type ??")
lvi.SubItems.Add(mFile.LastAccessTime.ToShortDateString & " " & mFile.LastAccessTime.ToShortTimeString) 'This isn't same as last modified ?
Next
If somebody knows how to do It please let me know, I want to have this in my Details view.
The linked answer provides an all-purpose way to get all the extended properties. With 300+ elements in newer Windows versions it is clearly overkill to fetch them all if you are only interested in one or two. This returns just the file type. A better approach might be to pass a "shopping list" of desired property names.
As before, you need to add a reference to Microsoft Shell Controls and Automation or Microsoft Shell Folder View Router based on your OS version.
Imports Shell32
Imports SHDocVw
Partial Friend Class Shell32Methods
Friend Shared Function GetShellFileProperty(filepath As String, index As Int32) As String
Dim shell As New Shell32.Shell
Dim shFolder As Shell32.Folder
shFolder = shell.NameSpace(Path.GetDirectoryName(filepath))
' get shell data for this file, cast to folder item
Dim shFolderItem = DirectCast(shFolder.Items().Item(Path.GetFileName(filepath)),
Shell32.ShellFolderItem)
If shFolderItem IsNot Nothing Then
Return shFolder.GetDetailsOf(shFolderItem, index)
Else
Return String.Empty
End If
End Function
...
End Class
Usage:
Dim lvi As ListViewItem
Dim fileType As String
For Each f As String In Directory.EnumerateFiles("C:\Temp\ShellTest")
fileType = Shell32Methods.GetShellFileProperty(f, 9)
lvi = New ListViewItem
lvi.Text = Path.GetFileName(f)
lvi.SubItems.Add(fileType)
lvFiles.Items.Add(lvi)
Next
Ideally, you'd want to create an Enum for the properties so the code could avoid magic numbers:
fileType = Shell32Methods.GetShellFileProperty(f, Shell32FileProps.FileType)
As noted elsewhere, the index of the ones >260 or so can change depending on the OS version. That could be easily modified to accept an Enum/Int array and return a list of values so as to prevent iterating all 300+ propertied to get one or three.
For filetype you can use lvi.SubItems.Add(MyFile.Extension)
and for the "last modified" date, of course the last modified! :D
lvi.SubItems.Add(MyFile.LastWriteTime.ToShortDateString)
Last write and last access are not the same ;)
I figured out another solution, I think this one is easier, at least for me :
Public Function ExProperty(filepath As String, PropertyItem As Integer)
Dim arrHeaders As New List(Of String)()
Dim shell As New Shell
Dim rFolder As Folder = shell.[NameSpace](Path.GetDirectoryName(filepath))
Dim rFiles As FolderItem = rFolder.ParseName(Path.GetFileName(filepath))
'I needed only File type so I looped to 2 only (2 is the file type in my case - Windows 10 -
' to see all available properties do a loop
' 0 To Short.MaxValue - 1" and then extract whatever property you like)
For i As Integer = 0 To 2
Dim value As String = rFolder.GetDetailsOf(rFiles, i).Trim()
arrHeaders.Add(value)
Next
Dim DesiredProperty As String
DesiredProperty = arrHeaders.Item(PropertyItem)
Return DesiredProperty
End Function
Usage with Listview just simply (this adds File type subitem):
Listview1_Item.SubItems.Add(ExProperty(filepath, 2))
As in all solutions, a reference to Microsoft Shell Controls and Automation must be set.

VB Import variable then use part 1 in dropdown and display part 2 to match selection in part 1

I'm using Visual studio to build a small utility.
I'm importing variables from a text file (this makes my program expandable in the future).
I'm running into a road block trying to split the variables into usable parts.
The text file is set up as such:
Game1:flshflhdlsfsdsfs
Game2:ugdjgndrgbdvdnjd
Game3:gnnereknengievke
And the code I've gathered from searching around trying to understand how I could do this is (It's gone through multiple rewrites but I feel this is probably the closest I've gotten):
Dim value As String = File.ReadAllText("Games.txt")
Dim cut_at As String = ":"
Dim x As Integer = InStr(value, cut_at)
Dim string_before As String = value.Substring(0, x - 2)
Dim string_after As String = value.Substring(x + cut_at.Length - 1)
Games_drp.Items.AddRange(string_before)
When I run a test like this, I get an error that String_before cannot be converted to an object. I tried switching "Dim string_before As String = value.Substring(0, x - 2)" to Dim string_before As Object = value.Substring(0, x - 2), but the dropdown that's supposed to be populated by at least one of the entries before the : has absolutely nothing in it.
Being pretty new at VB and feeling like I've exhausted pretty much every way I could think of searching in google and trying to piece together various bits of information, I figure I'd try asking my own direct question:
How would I go about reading all the lines from a text file, then splitting before the : to fill a combobox, and using a label to display the string after the : matching which ever entry is selected in the dropdown.
Thanks in advance for any help.
EDIT with full code:
Imports System.IO
Public Class Saves_frm
Private Sub Saves_frm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value As String = File.ReadAllText("Games.txt")
Dim cut_at As String = ":"
Dim x As Integer = InStr(value, cut_at)
Dim string_before As String = value.Substring(0, x - 2)
Dim string_after As String = value.Substring(x + cut_at.Length - 1)
Games_drp.Items.AddRange(string_before)
End Sub
End Class
When run as is, I get an error that 'string_before' can't be converted from a string to an object, but when I make the following change from:
Dim string_before As String = value.Substring(0, x - 2)
to:
Dim string_before As Object = value.Substring(0, x - 2)
The error goes away, but the dropdown remains blank.
It's easier to use File.ReadAllLines, as it returns an array with all the file's lines. Then, you can loop through the lines, splitting each line and adding the result to the ListBox. This should be an example, but feel free to correct any mistakes I made, as I wrote it on my phone and it's been a long time since I used VB.
Dim lines() As String = File.ReadAllLines("file.txt")
For Each line As String In lines
Dim split() As String = line.Split(":"c)
gDic.Add(split(0), split(1))
Next
EDIT: Then, you most certainly want a dictionary that contains the name and the data, check the updated code.
Then, add the names by looping through gDic.Keys. When a name is selected, access its value with gDic("key").

Can I compute the name of a variable in VB.net

I want to know if it is possible to compute the name of a variable in VB.net. I need to open a bunch of text files at runtime. The exact number will be variable. I wanted to do something along the lines of:
For j = 1 to Filecount
Dim Filename As String = "File"&j
Dim File & j As New System.IO.StreamWriter(Filename)
Next
When I tried this, VB.net said it didn't like it. Is this possible?
I think you would be better off using a dictionary, which would allow you to get back to the appropriate stream writer using the filename later:
Dim fileDictoinary As New Dictionary(Of String, System.IO.StreamWriter)
For j = 1 To Filecount
Dim Filename As String = "File" & j
fileDictoinary.Add(Filename, New System.IO.StreamWriter(Filename))
Next
Then at a later time you can access the streamwriter using the filename in the dictionary:
Dim file4StreamWriter = fileDictoinary("File4")
file4StreamWriter.Write(True)

Renaming all files in a folder

I'm wondering if it's possible to rename all the files in a folder with a simple program, using vb.NET
I'm quite green and not sure if this is even possible.
Lets say there is a folder containing the files:
Text_Space_aliens.txt, fishing_and_hunting_racoons.txt and mapple.txt.
Using a few credentials:
Dim outPut as String = "TextFile_"
Dim fileType as String = ".txt"
Dim numberOfFiles = My.Computer.FileSystem.GetFiles(LocationFolder.Text)
Dim filesTotal As Integer = CStr(numberOfFiles.Count)
Will it be possible to rename these, regardless of previous name, example:
TextFile_1.txt, TextFile_2.txt & TextFile_3.txt
in one operation?
I think this should do the trick. Use Directory.GetFiles(..) to look for specific files. Enumerate results with a for..each and move (aka rename) files to new name. You will have to adjust sourcePath and searchPattern to work for you.
Private Sub renameFilesInFolder()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim i As Integer = 0
For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
In your title you state something about chronologically, but within your question you never mentioned it again. So I did another example ordering files by creationTime.
Private Sub renameFilesInFolderChronologically()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
I've never done Lambdas in VB.net but tested my code and it worked as intended. If anything goes wrong please let me know.

Adding multiple strings to a listbox from text

I have a text file I need to get multiple strings from, I can sort of do it but it only shows the first string in the listbox
When we tried with XML reader it was collecting everything in the XML that was tagged Object Identifier along with the cameras
I need to look for lines similar to the following, there could be any amount
Object Identifier="./Cameras/MyCamera" Label="Standard Camera" Name="MyCamera" Type="Camera"
key identifiers:
./Cameras/
Label="Standard Camera"
Type="Camera"
I could use "MyCamera" after ./Cameras/ or Name="MyCamera" both of these are common in each occurrence of the lines
in my example below it has the file I wish to read it should list 3 cameras
https://www.dropbox.com/s/dy7r2auf9vv0m7g/testvb.zip
The XML is generated by Thea render, its the scene file with the model, lights etc taken out so it just leaves cameras and some core settings
Thanks to varocarbas, this is the code that solves my problem:
Dim path As String = "C:\Users\jen\Desktop\test\temp.xml"
Dim settings As System.Xml.XmlReaderSettings = New System.Xml.XmlReaderSettings()
settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment
Using reader As System.Xml.XmlReader = System.Xml.XmlReader.Create(path)
While (reader.Read())
If (reader.NodeType = System.Xml.XmlNodeType.Element) Then
If (reader.Name = "Object") Then
'Object Identifier="./Cameras/MyCamera" Label="Standard Camera" Name="MyCamera" Type="Camera"
Dim Identifier As String = reader.GetAttribute("Identifier") '"./Cameras/MyCamera"
Dim Label As String = reader.GetAttribute("Label") '"Standard Camera"
Dim Name As String = reader.GetAttribute("Name") '"MyCamera"
Dim Type As String = reader.GetAttribute("Type") '"Camera"
Dim wholeString As String = Name 'WHOLE STRING TO BE ADDED TO THE LISTBOX
'Adding the string to ListBox1
If (wholeString.Trim.Length > 0) And Type = "Camera" Then
ListBox1.Items.Add(wholeString)
End If
End If
End If
End While
End Using
You can use the XMLReader I proposed in another answer and do the following modifications on it:
Dim path As String = "temp.txt"
Dim settings As System.Xml.XmlReaderSettings = New System.Xml.XmlReaderSettings()
settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment
Using reader As System.Xml.XmlReader = System.Xml.XmlReader.Create(path)
While (reader.Read())
If (reader.NodeType = System.Xml.XmlNodeType.Element) Then
If (reader.Name = "Object") Then
'Object Identifier="./Cameras/MyCamera" Label="Standard Camera" Name="MyCamera" Type="Camera"
Dim Identifier As String = reader.GetAttribute("Identifier") '"./Cameras/MyCamera"
Dim Label As String = reader.GetAttribute("Label") '"Standard Camera"
Dim Name As String = reader.GetAttribute("Name") '"MyCamera"
Dim Type As String = reader.GetAttribute("Type") '"Camera"
Dim wholeString As String = Identifier & " - " & Label & " - " & Name & " - " & Type 'WHOLE STRING TO BE ADDED TO THE LISTBOX
'Adding the string to ListBox1
If (wholeString.Trim.Length > 0) Then
ListBox1.Items.Add(wholeString)
End If
End If
End If
End While
End Using
This code retrieves all the information you want and stores it in LisBox1 by putting " - " to separate each element. This is information more than enough and you should be the one performing any further change, for example: converting "./Cameras/MyCamera" into "./Cameras/" (there is an indication of how to do that in my previous code); or change the way the different items are displayed in the listBox (or perhaps you want to include one listBox per element: one for identifiers, another for labels, etc.).