get full string before first second third etc. split - vb.net

I have a file location and I need to check if it exists.
The way I wan't to do it is like this:
Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
If System.IO.File.Exists(route) Then
MsgBox("BESTAAT HET WERKT!")
Else
Dim subroute() As String = route.Split("\"c)
Dim counting As Integer = route.Split("\"c).Length - 1
For count2 As Integer = 0 To counting - 1
Dim firstbackslash As Integer = route.IndexOf("\")
Dim backslash As Integer = route.IndexOf("\", firstbackslash + 1)
Dim firstPart As String = route.Substring(0, backslash)
MsgBox(firstPart)
Next
What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
But I cant find something like this on the internet nor with some messing around...

Here is an algorithm that that will give you all the paths starting from the root and building up to the final path including the filename. You can use this to check for each folder and create them as you go if they don't exist:
Sub Main()
Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
Dim fi As New System.IO.FileInfo(route)
If Not fi.Exists Then
Dim fileName As String = Path.GetFileName(route)
Dim di As DirectoryInfo = fi.Directory
Dim pathStack As New Stack(Of String)()
pathStack.Push(di.Name)
While Not IsNothing(di.Parent)
di = di.Parent
pathStack.Push(di.Name)
End While
Dim curPath As String = ""
While pathStack.Count > 0
curPath = Path.Combine(curPath, pathStack.Pop)
' ... do something with "curPath" in here ...
' ... like check for existence and create it ...
Console.WriteLine(curPath)
End While
curPath = Path.Combine(curPath, fileName)
' ... do something with "curPath" in here ...
' ... this is the full path including the file on the end ...
Console.WriteLine(curPath)
End If
Console.Write("Press Enter to quit...")
Console.ReadLine()
End Sub
Output:
C:\
C:\testing1
C:\testing1\testing2
C:\testing1\testing2\testing3
C:\testing1\testing2\testing3\testing4
C:\testing1\testing2\testing3\testing4\testing5
C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt
Press Enter to quit...

Don't use string mnaipulation to work with file or folder paths. use the Path class.
One option:
Private Function GetExistingSubPath(fullPath As String) As String
If Directory.Exists(fullPath) OrElse File.Exists(fullPath) Then
Return fullPath
End If
Dim subPath = Path.GetDirectoryName(fullPath)
If subPath Is Nothing Then
Return Nothing
End If
Return GetExistingSubPath(subPath)
End Function
Sample usage:
Dim fullPath = "C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt"
Dim existingSubPath = GetExistingSubPath(fullPath)
Console.WriteLine(existingSubPath)

What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
Noooooooooooo!
That's not how to do it at all! The file system is volatile: things can change between each of those checks. Moreover, file existence is only one of many things that can stop file access.
It's much better practice to try to access the file in question, and then handle the exception if it fails. Remember, because of the prior paragraph you have to be able to handle exceptions here anyway. .Exists() doesn't save you from writing that code. And each check is another round of disk access, which is about the slowest thing it's possible to do in a computer... even slower than unrolling the stack for an exception, which is the usual objection to this idea.

I fixed it, know I can check if multiple text files are at the locations I need, if there not I place the Textfiles at the location I need them. Then I can add something in it. (I need to put a Location of something else in it.)
Dim een As String = "C:\testing1\testing2\testing7\testing1\testing1\text.txt"
Dim twee As String = "C:\testing1\testing2\testing7\testing2\testing1\text.txt"
Dim drie As String = "C:\testing1\testing2\testing7\testing3\testing1\text.txt"
Dim vier As String = "C:\testing1\testing2\testing7\testing4\testing1\text.txt"
Dim Files As String() = {een, twee, drie, vier}
For Each route As String In Files
If System.IO.File.Exists(route) Then
MsgBox("BESTAAT HET WERKT!")
Else
Dim subroute() As String = route.Split("\"c)
Dim counting As Integer = route.Split("\"c).Length - 1
Dim tel As Integer = route.Substring(route.LastIndexOf("\") + 1).Count
Dim bestandnaam As String = route.Substring(route.LastIndexOf("\") + 1)
For count2 As Integer = 0 To route.Length - tel - 1
Dim firstbackslash As Integer = route.IndexOf("\", count2)
Dim backslash As Integer = route.IndexOf("\", count2)
Dim Mapnaam As String = route.Substring(0, backslash)
count2 = firstbackslash
If System.IO.Directory.Exists(Mapnaam) Then
Else
System.IO.Directory.CreateDirectory(Mapnaam)
End If
Next
If System.IO.File.Exists(route) Then
Else
Dim objStreamWriter As System.IO.StreamWriter
objStreamWriter = New System.IO.StreamWriter(route)
Dim label As String
Select Case route
Case een
label = "een"
Case twee
label = "twee"
Case drie
label = "drie"
Case vier
label = "vier"
End Select
Dim value As String = InputBox("Route invullen naar " & label)
'Dim objStreamWriter As New System.IO.StreamWriter(route)
objStreamWriter.Write(value)
objStreamWriter.Close()
'Using sw As System.IO.StreamWriter = System.IO.File.AppendText(route)
' sw.WriteLine(value)
'End Using
End If
End If
Next route

Related

How can i find a string in a txt file and linenumber

I would like to make a "Tolerance-calculator"
The user gives an input as string. For example:"D6" now i have to search this in the .txt file and read the next line.
I read the file like this:
Dim Findstring = IO.File.ReadAllText("....\Toleranz0.txt")
How can i find the string an the next line after the string?
Maybe:
Findstring.contains("D6") 'gives a Boolean
How does i get the correct line?
Convert your string to an array using String.Split() and find the next index or 2 indexes after "D6":
Private Sub Funcy()
Dim Findstring As String = IO.File.ReadAllText("....\Toleranz0.txt")
Dim MyCollection() As String = Findstring.Split()
Dim result As String = MyCollection(Array.IndexOf(MyCollection, "D6") + 2)
MessageBox.Show(result)
End Sub
Here's an example using ReadAllLines() as suggested by Blorgbeard:
Dim lines() As String = IO.File.ReadAllLines("....\Toleranz0.txt")
Dim index As Integer = Array.IndexOf(lines, "D6")
If index <> -1 AndAlso index <= lines.Count - 2 Then
Dim targetLine As String = lines(index + 1)
' ... do something with "targetLine" ...
Else
' either the line was not found, or there was no line after the found line
End If

If directory exists in a VB.NET code

I have the following code to create a directory, the task accepts a recordcount and every time the recordcount reaches the required number, say 1000 records, a new directory is created. If the task is run a second time it will add another 1000 records to the existing directories, I want it to skip these existing directories and create a new one. I've tried adding various ifexists, but mess it up all the time, any help would be appreciated
Public Sub Main()
Dim SourceDirectory As String = "E:\Data"
Dim TargetDirectory As String = "E:\CN"
Dim FileExtensionsToProcess As String = "CON*.pdf"
Dim FileCounter As Integer = 0
Dim FolderName As Integer = 1
Dim recordcount As Integer
recordcount = CInt(Dts.Variables("RecordCount").Value)
For Each FileName As String In System.IO.Directory.GetFiles(SourceDirectory, FileExtensionsToProcess)
Dim FileOnly As String = System.IO.Path.GetFileName(FileName)
Try
If Not IO.Directory.Exists(IO.Path.Combine(TargetDirectory, FolderName.ToString())) Then
IO.Directory.CreateDirectory(IO.Path.Combine(TargetDirectory, FolderName.ToString()))
End If
IO.File.Move(FileName, IO.Path.Combine(TargetDirectory, IO.Path.Combine(FolderName.ToString(), FileOnly)))
Catch
End Try
FileCounter += 1
If (FileCounter Mod recordcount) = 0 Then
FolderName += 1
End If
Next
Dts.TaskResult = ScriptResults.Success
End Sub
Okay. The full solution is shown below and then I will explain some of it.
Public Sub Main()
Dim SourceDirectory As String = "E:\Data"
Dim TargetDirectory As String = "E:\CN"
Dim FileExtensionsToProcess As String = "CON*.pdf"
Dim FileCounter As Integer = 0
Dim FolderName As Integer = 1
Dim recordcount As Integer = CInt(Dts.Variables("RecordCount").Value)
Dim targetDir As String = SetOutputFolder(TargetDirectory, FolderName, recordcount)
For Each FileName As String In Directory.GetFiles(SourceDirectory, FileExtensionsToProcess)
Dim FileOnly As String = Path.GetFileName(FileName)
'Try - Leave this out to observe any exceptions, then add handling when you see any
' Check for file name conflicts before moving
File.Move(FileName, Path.Combine(targetDir, FileOnly))
'Catch
'End Try
FileCounter += 1
If FileCounter >= recordcount Then
FolderName += 1
targetDir = SetOutputFolder(TargetDirectory, FolderName, recordcount)
FileCounter = Directory.GetFiles(targetDir).Count
End If
Next
End Sub
Private Function SetOutputFolder(baseDir As String, ByRef folderName As Integer, ByRef recordCount As Integer) As String
Dim targetDir = Path.Combine(baseDir, folderName.ToString())
Dim filecounter = 0
While Directory.Exists(targetDir)
filecounter = Directory.GetFiles(targetDir).Count
If filecounter >= recordCount Then
folderName += 1
targetDir = Path.Combine(baseDir, folderName.ToString())
Else
Exit While
End If
End While
If Not Directory.Exists(targetDir) Then
Directory.CreateDirectory(targetDir)
End If
Return targetDir
End Function
The additional function I created solves a few problems. Note that it is passing the folder counter and the record count as references ByRef folderName As Integer, ByRef recordCount As Integer, so it can continue with correct values after getting the right directory. It will search for the target directory, starting at 1, and for each directory it finds it will check to see if it is full or not. If it is, then it will carry on, otherwise it will select that directory.
Within this it also checked if the directory exists and if not, creates it before exiting, this removes the extra If statements that are needed throughout and puts them in one place.

Generate multiple files in a loop using visual basic

I am new to Visual Basic.
I wonder if I wanna generate multiple files in a while loop. It seems that the FILESTREAM cannot be reused even I set it into nothing at the end of loop.
Dim fs as FILESTREAM = nothing
Dim i as integer = 0
Dim path as string = "c:\users\...\Desktop\"
Dim name as string = nothing
while i<10
name = path + i.tostring
fs=File.Create(name)
i+=1
fs=nothing
end while
Thank you very much!
It's not clear if you're using the FileStream just to create a blank file or if you're planning on performing other operations against the new files. If you're just trying to create empty files and manipulate them later, after creation, then this should work:
Sub Main()
Dim i As Integer = 0
' You can use properties of My.Computer to find the current user's Desktop
Dim path As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim fileName As String = String.Empty
While i < 10
fileName = path & "\" & i.ToString
System.IO.File.Create(fileName)
i += 1
End While
End Sub

Search line in text file and return value from a set starting point vb.net

I'm currently using the following to read the contents of all text files in a directory into an array
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
Within the text files are only 6 lines that all follow the same format and will read something like
forecolour=black
I'm trying to then search for the word "forecolour" and retrieve the information after the "=" sign (black) so i can then populate the below code
AllDetail(numfiles).uPath = ' this needs to be the above result
I've only posted parts of the code but if it helps i can post the rest. I just need a little guidance if possible
Thanks
This is the full code
Dim numfiles As Integer
ReDim AllDetail(0 To 0)
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
lb1.Items.Clear()
For Each txtfi In lynxin.GetFiles("*.txt")
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
ReDim Preserve AllDetail(0 To numfiles)
AllDetail(numfiles).uPath = 'Needs to be populated
AllDetail(numfiles).uName = 'Needs to be populated
AllDetail(numfiles).uCode = 'Needs to be populated
AllDetail(numfiles).uOps = 'Needs to be populated
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
End Sub
AllDetail(numfiles).uPath = Would be the actual file path
AllDetail(numfiles).uName = Would be the detail after “unitname=”
AllDetail(numfiles).uCode = Would be the detail after “unitcode=”
AllDetail(numfiles).uOps = Would be the detail after “operation=”
Within the text files that are being read there will be the following lines
Unitname=
Unitcode=
Operation=
Requirements=
Dateplanned=
For the purpose of this array I just need the unitname, unitcode & operation. Going forward I will need the dateplanned as when this is working I want to try and work out how to only display the information if the dateplanned matches the date from a datepicker. Hope that helps and any guidance or tips are gratefully received
If your file is not very big you could simply
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
For each line in allLines
Dim parts = line.Split("="c)
if parts.Length = 2 andalso parts(0) = "unitname" Then
AllDetails(numFiles).uName = parts(1)
Exit For
End If
Next
If you are absolutely sure of the format of your input file, you could also use Linq to remove the explict for each
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname"))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
EDIT
Looking at the last details added to your question I think you could rewrite your code in this way, but still a critical piece of info is missing.
What kind of object is supposed to be stored in the array AllDetails?
I suppose you have a class named FileDetail as this
Public class FileDetail
Public Dim uName As String
Public Dim uCode As String
Public Dim uCode As String
End Class
....
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
' Get the FileInfo array here and dimension the array for the size required
Dim allfiles = lynxin.GetFiles("*.txt")
' The array should contains elements of a class that have the appropriate properties
Dim AllDetails(allfiles.Count) as FileDetail
lb1.Items.Clear()
For Each txtfi In allfiles)
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
AllDetails(numFiles) = new FileDetail()
AllDetails(numFiles).uPath = txtfi.FullName
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("unitcode="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("operation="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uOps = line.Split("="c)(1)
End If
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
Keep in mind that this code could be really simplified if you start using a List(Of FileDetails)

Copying data from text file to array

I'm trying to copy data from text file to array, I got error Index was outside the bounds of the array.
Dim vstring(-1) As String
Dim vid(-1) As String
Dim index As Integer
Dim vText As String = ""
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"
Dim vAvgValue As Integer
Dim vErrorMsg As String = ""
If (Txt_IdNumber.Text).Length = 5 Then
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine()
vstring = vText.Split(",")
vid(index) = vstring(0)'error
index = index + 1
Loop
Dim vstring() as String
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"
If Txt_IdNumber.Text.Length = 5 Then
Using rvSR As New IO.StreamReader(vFileName)
vstring = rvSR.ReadLines().Select(Function(s) s.Split(","c)(0)).ToArray()
End Using
End If
First, you should probably declare vstring as an unsized array. Like this:
Dim vString() as string
Second, Since you don't know how many lines you need, declare vid as list. Like this:
Dim vid as List(of string)
Then, before you split the string, you should make sure it actually contains a comma. Like this:
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine()
If vText.Contains(",") Then
vstring = vText.Split(",")
vid.add(vstring(0))
End If
Loop
'at the end, you can convert vid from a list to an array, if you want
Dim arr() as string = vid.ToArray()