Getting variables form text file, then setting a new variable - vb.net

I'm creating a code for the computers at work. I had to make an "Install" program. I didn't know how to do it properly but I found a way to do it.
When I "Install" the program on a other computer I have my USB-stick and copy it to the local disk at the computer.
Now I start the program for the first time at their computer and this code run's
and then I got an error here because Program is not yet divined:
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim Pathproj As String = AppDomain.CurrentDomain.BaseDirectory
Dim Pathfile As String = Pathproj.Replace("bin\Debug\", "Bestanden\Locatie.txt")
Dim Program As String = System.IO.File.ReadAllText(Pathfile)
'Deze bestanden worden aangemaakt en er wordt automatisch een route ingezet.
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim lBibliotheek As String = System.IO.File.ReadAllText(Program & "Bibliotheek.txt")
Dim lExcel_autonummering As String = System.IO.File.ReadAllText(Program & "Excelbestand autonummering.txt")
Dim lLocatie_telbestanden As String = System.IO.File.ReadAllText(Program & "Locatie telbestanden.txt")
Dim lMapnamen As String = System.IO.File.ReadAllText(Program & "Mapnamen.txt")
Dim lOrderschijf As String = System.IO.File.ReadAllText(Program & "Zoek schijf.txt")
Because when the form2_load I do this and then I wan't to divine that string.
Public Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Locatie_05Kuipers As String
If System.IO.File.ReadAllText(Pathfile) = "" Then
'If System.IO.File.ReadAllText("C:\testing1\testing2\testing7\testing1\testing1\text.txt") = "" Then
Locatie_05Kuipers = InputBox("Vul hier de Locatie waar je start bestanden moeten staan. Bijvoorbeeld: K:\Inventor\Instalprogram\ ")
If System.IO.File.Exists(Pathfile) Then
System.IO.File.Delete(Pathfile)
End If
Dim objStreamWriter As StreamWriter
objStreamWriter = New StreamWriter(Pathfile)
objStreamWriter.WriteLine(Locatie_05Kuipers & "\03 - Locaties")
objStreamWriter.Close()
ButtonInstal.Visible = True
Exit Sub
Else
End If
So how or where do I need to put my strings?

You can save a path in your settings, and every time you need it, you can create the file and put your data in it.
For example:
Dim pathString As String = My.Settings.filePath
Dim fullPath = Path.Combine(pathString, "Locatie.txt")
If Not Directory.Exists(pathString) Then
Directory.CreateDirectory(pathString)
File.Create(fullPath)
Else
If Not File.Exists(pathString) Then
File.Create(fullPath)
Else
Console.WriteLine($"File {fullPath}already exists.")
End If
End If

Related

Making a program that zip files but having error The process cannot access the file because it is being used by another process

I am trying to make a program that will zip all the files in the same folder.
But I'm having issues with it. It's giving me an error saying the file is being used by another process.
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
Dim fileName As String = path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub
I just couldn't figure out what's causing the issue.
as seen in comment, you must exclude your running application from the file list :
add
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
in for loop
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
Dim fileName As String = Path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub

Why does Virtual Basic say it cannot access the file?

I am creating a solid edge macro that saves a 3D file in solid edge in three different types simultaneously.
owever, I am new to vb.net some I am having some difficulty.
When I run the program, the first pop up says "this file already exists, do you want to overwrite it?".
The next pop up says "cannot access this file" and then the program stops.
Why can vb.net not access the file? It is open in solid edge in the background.
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub saveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles saveBtn.Click
Dim objApplication As SolidEdgeFramework.Application = Nothing
Dim objDocument As SolidEdgeFramework.SolidEdgeDocument = Nothing
Dim objPropertySets As SolidEdgeFramework.PropertySets = Nothing
Dim objProperties As SolidEdgeFramework.Properties = Nothing
Dim objProperty As SolidEdgeFramework.Property = Nothing
Dim FileName As String
Dim i, j As Integer
Dim NewFileName1 As String
Dim NewFileName2 As String
Dim NewFileName3 As String
Dim Extensions(2) As String
Extensions(0) = ".step"
Extensions(1) = ".x_t"
Extensions(2) = ".igs"
Try
objApplication = Marshal.GetActiveObject("SolidEdge.Application")
objDocument = objApplication.ActiveDocument
objPropertySets = objDocument.Properties
For i = 1 To objPropertySets.Count
objProperties = objPropertySets.Item(i)
For j = 1 To objProperties.Count
objProperty = objProperties.Item(j)
Next
Next
FileName = objProperty.Name
NewFileName1 = FileName & Extensions(0)
NewFileName2 = FileName & Extensions(1)
NewFileName3 = FileName & Extensions(2)
objDocument.SaveAs("C:\Folder", NewFileName1)
objDocument.SaveAs("C:\Folder", NewFileName2)
objDocument.SaveAs("C:\Folder", NewFileName3)
'objDocument.SaveAs(NewFileName1)
'objDocument.SaveAs(NewFileName2)
'objDocument.SaveAs(NewFileName3)
Catch ex As Exception
txt.Text = " Error"
Finally
If Not (objDocument Is Nothing) Then
Marshal.ReleaseComObject(objDocument)
objDocument = Nothing
End If
If Not (objApplication Is Nothing) Then
Marshal.ReleaseComObject(objApplication)
objApplication = Nothing
End If
End Try
End Sub
End Class

Wait until media element has naturalDuration information

I need to make a loop to look at a lot of mp3 files and getting their naturalDuration property using a mediaElement. The problem is that mediaElement need some time to load every single file and .source property works like async process (I think) because I have to click two times on below code if I want to obtain naturalDuration property. First click I have just 00:00:00 value, second clik give me real value.
Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
mediaElement.Source = New Uri("\\Mac\Home\Desktop\NOVEDADES01\AbrahamMateo-OldSchool.mp3")
textBlock.Text = mediaElement.NaturalDuration.ToString
End Sub
If I try to wait after .Source instruction, the application keeps on loop.
Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
mediaElement.Source = New Uri("\\Mac\Home\Desktop\NOVEDADES01\AbrahamMateo-OldSchool.mp3")
Do
Loop Until mediaElement.NaturalDuration.TimeSpan.TotalSeconds > 0
textBlock.Text = mediaElement.NaturalDuration.ToString
End Sub
I also have try set .source through an async process and wait for mediaOpenend event, but it look like mediaElemento can not end until the first click was ending
How could I get real value of naturalDuration inside one single process or function just after set .source property and without playing the file?
Thanks a lot!!
Ok, late and may be not so elegant but this was my solution for getting duration of a mp3 file. I used MusicProperties Class.
Public Function infoMP3(elfichero As String) As String
Dim salida As String = ""
Dim miTask = Task.Run(Async Function() As Task(Of String)
Dim musicFile As StorageFile = Await StorageFile.GetFileFromPathAsync(elfichero)
Dim FileProperties As StorageItemContentProperties = musicFile.Properties
Dim musicFileProperties As MusicProperties = Await FileProperties.GetMusicPropertiesAsync()
Dim tiempo = musicFileProperties.Duration
Dim horas As String
If tiempo.Hours < 10 Then
horas = "0" & tiempo.Hours.ToString
Else
horas = tiempo.Hours.ToString
End If
Dim minutos As String
If tiempo.Minutes < 10 Then
minutos = "0" & tiempo.Minutes.ToString
Else
minutos = tiempo.Minutes.ToString
End If
Dim segundos As String
If tiempo.Seconds < 10 Then
segundos = "0" & tiempo.Seconds.ToString
Else
segundos = tiempo.Seconds.ToString
End If
Dim autor = musicFileProperties.Artist
Dim titulo = musicFileProperties.Title
Dim presalida As String = "[" & horas & ":" & minutos & ":" & segundos & "];[" & titulo & "];[" & autor & "] " & elfichero
Return presalida
End Function)
miTask.Wait()
salida = miTask.Result
Return salida
End Function
To get access to the files later on Windows 10, you have to save permission for the files and/or folders. Do this when you select them.
...
Dim listToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(rutaS)
...
where rutaS is an SotorageFolder object.

How to add a string to multiple string for printing external

This is going to be a long one, but easy fix.
So i've manage to convert a pdf to string, then able to print an external pdf simply by putting the name of the file in a textbox.
I've also figured how to extract certain text from the pdf string, now the certain text are also files located in an external location (I use c:\temp\ for testing).
Which leaves me with one problem, the text I extract, I use shellexecute to print, works fine if its one string. however, If the file name I extract is more than one it will count it as a single string, thus adding the location and .pdf to that one string. instead of the two or more strings. which will do something like this:
As you can see, it will send that to the printer. I want to send one at a time to the printer. like this:
I've tried using an Arraylist and various methods. but my own lack of knowledge, I cannot figure it out.
I'm thinking a "for loop" will help me out. any ideas?
Below is my code.
Dim pdffilename As String = Nothing
pdffilename = RawTextbox.Text
Dim filepath = "c:\temp\" & RawTextbox.Text & ".pdf"
Dim thetext As String
thetext = GetTextFromPDF(filepath) ' converts pdf to text from a function I didnt show.
Dim re As New Regex("[\t ](?<w>((asm)|(asy)|(717)|(ssm)|(715)|(818))[a-z0-9]*)[\t ]", RegexOptions.ExplicitCapture Or RegexOptions.IgnoreCase Or RegexOptions.Compiled) ' This filters out and extract certain keywords from the PDF
Dim Lines() As String = {thetext}
Dim words As New List(Of String)
For Each s As String In Lines
Dim mc As MatchCollection = re.Matches(s)
For Each m As Match In mc
words.Add(m.Groups("w").Value)
Next
RawRich4.Text = String.Join(Environment.NewLine, words.ToArray)
Next
'This is where I need help with the code. how to have "words" putout "c:\temp\" & RawRich4.Text & ".pdf" with each keyword name
Dim rawtoprint As String = String.Join(Environment.NewLine, words.ToArray)
Dim defname As String = Nothing
defname = RawRich4.Text
rawtoprint = "c:\temp\" & RawRich4.Text & ".pdf"
Dim psi As New System.Diagnostics.ProcessStartInfo()
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
psi.FileName = (rawtoprint) ' this is where the error occurs it doesn't send both files separately to the printer, it tries to send it as one name
MessageBox.Show(rawtoprint) ' This is just to test the output, this will be removed.
'Process.Start(psi)
End Sub
Updated.
Imports System.Text.RegularExpressions
Module Program
Sub Main()
Dim pdffilename As String = RawTextbox.Text
Dim filepath = "c:\temp\" & RawTextbox.Text & ".pdf"
Dim thetext As String
thetext = GetTextFromPDF(filepath) ' converts pdf to text from a function I didnt show.
'thetext = "Random text here and everywhere ASM00200207 1 1 same here bah boom 12303 doh hel232 ASM00200208 1 2 "
Dim pattern As String = "(?i)[\t ](?<w>((asm)|(asy)|(717)|(ssm)|(715)|(818))[a-z0-9]*)[\t ]"
For Each m As Match In rgx.Matches(thetext, pattern)
'Console.WriteLine("C:\temp\" & Trim(m.ToString) & ".pdf")
RawPrintFunction("C:\temp\" & Trim(m.ToString) & ".pdf")
Next
End Sub
Function RawPrintFunction(ByVal rawtoprint As String) As Integer
Dim psi As New System.Diagnostics.ProcessStartInfo()
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
MessageBox.Show(rawtoprint) This will be removed, this is just for testing to see what files will be printed
'Process.Start(psi) This will be uncomment.
return 0
End Function
End Module
If I don't misunderstand the code -since I can't test and run it here- you can iterate through file names stored in words variable and send it to printer. Following is an example on how to do that :
....
....
Dim Lines() As String = {thetext}
Dim words As New List(Of String)
For Each s As String In Lines
Dim mc As MatchCollection = re.Matches(s)
For Each m As Match In mc
words.Add(m.Groups("w").Value)
Next
RawRich4.Text = String.Join(Environment.NewLine, words.ToArray)
Next
For Each fileName As String In words
Dim rawtoprint As String
rawtoprint = "c:\temp\" & fileName & ".pdf"
Dim psi As New System.Diagnostics.ProcessStartInfo()
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
psi.FileName = (rawtoprint) ' this is where the error occurs it doesn't send both files separately to the printer, it tries to send it as one name
MessageBox.Show(rawtoprint) ' This is just to test the output, this will be removed.
'Process.Start(psi)
Next

How do I copy a file that contains the same string as the directory?

I currently have these directories:
C:\testfolder\100
C:\testfolder\101
C:\testfolder\102
and I have these files in the same directory:
C:\testfolder\file-100.txt
C:\testfolder\file-101.txt
C:\testfolder\file-102.txt
What I was trying to do in VB is move text file file-100.txt to the 100 directory. Same for text file file-101.txt, move it to its pertaining folder 101.
My question is how can I write a loop so that my program matches part of the string of my text file name and move it to the matching folder name? Moving one file at a time wouldn't be effecient since I have hundreds of directories and files to apply this to.
Edit:
I'm somewhat familiar with VB. I was having trouble with the logical part of this, in which I couldn't think of a way to write a loop so that it can transfer the files for me.
Without error checking, this would be a simple routine to move those files. It's based on your file names being consistent:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim homePath As String = "c:\testfolder"
Dim files() As String = Directory.GetFiles(homePath, "*.txt")
For Each f As String In files
Dim fileName As String = Path.GetFileName(f)
Dim destPath As String = Path.GetFileNameWithoutExtension(fileName)
destPath = destPath.Split("-")(1)
destPath = Path.Combine(homePath, destPath)
Dim destFile As String = Path.Combine(destPath, fileName)
File.Move(f, destFile)
Next
End Sub
This just gets the list of text files in your directory, parses the file name to get just the number value (100, 101, etc), and then reconstructs the new path. It assumes the directories exist, too.
You can use regular expression to find matched pattern
Dim dir As String = "C:\testfolder\"
Dim fileList() As String = {"C:\testfolder\file-100.txt", _
"C:\testfolder\file-101.txt", _
"C:\testfolder\file-102.txt"}
Dim pattern As New Regex(Replace(dir, "\", "\\") & "file-([0-9]+)[.]txt")
For Each value As String In fileList
Dim match As Match = pattern.Match(value)
If match.Success Then
MsgBox("move from " & dir & " to " & dir & match.Groups(1).Value)
End If
Next
Make sure you have import RegularExpressions.
Imports System.Text.RegularExpressions
Private Sub organizeFiles(ByVal folderPath As String)
For Each filePath As String In Directory.GetFiles(folderPath, "*.txt")
Dim destinationFilePath As String = getDestinationFilePath(filePath)
If destinationFilePath IsNot Nothing Then
File.Move(filePath, destinationFilePath)
End If
Next
End Sub
Private Function getDestinationFilePath(ByVal filePath As String) As String
Const fileNamePrefix As String = "file-"
Dim fileName As String = Path.GetFileName(filePath)
Dim fileNameWithoutExtension As String = Path.GetFileNameWithoutExtension(filePath)
If Not fileNameWithoutExtension.StartsWith(fileNamePrefix) Then
Return Nothing
End If
Dim folderName As String = fileNameWithoutExtension.Substring(fileNamePrefix.Length)
Dim fileFolderPath As String = Path.GetDirectoryName(filePath)
Dim destinationFolderPath As String = Path.Combine(fileFolderPath, folderName)
Dim destinationFilePath As String = Path.Combine(destinationFolderPath, fileName)
Return destinationFilePath
End Function