How to declare a path of file in vb.net? - vb.net

I'm going to do something like this,
If txt1.Text = "A" And txt2.Text = "B" Then
"path of my file which name is = c:/A.B"
End If
If txt1.Text = "C" And txt2.Text = "D" Then
"path of my file which name is = c:/C.D"
End If
How I'm going to do something like this ? I'm using vb.net

Another approach would be to use Path.Combine.
Declare a function first:
Private Function CreatePath(ByVal fileName As String,
ByVal extension As String) As String
Return Path.Combine("C:\", fileName & "." & extension)
End Function
Then call this wherever needed.
Dim Path as string
If txt1.Text = "A" And txt2.Text = "B" Then
"path of my file which name is = c:/A.B"
Path = CreatePath("A", "B")
End If
If txt1.Text = "C" And txt2.Text = "D" Then
"path of my file which name is = c:/C.D"
Path = CreatePath("C", "D")
End If

Use the String.Format method to concatenate them together.
Dim path As String = String.Format("c:/{0}.{1}", txt1.Text, txt2.Text)
Function:
Private Function ConPath(a As String, b As String) As String
Return String.Format("c:/{0}.{1}", a, b)
End Function

you can do this by simply writing this
"path of my file which name is = c:\" & txt1.Text & "." & txt2.Text

Related

VB.net Check items in a text doc and see if it's in a folder

I have a text document with a list of file names and their extensions. I need to go through this list and check a directory for the existence of each file. I then need to output the result to either foundFilesList.txt or OrphanedFiles.txt. I have two approaches to this function, and neither is working. The first example uses a loop to cycle through the text doc. The second one doesn't work it never sees a match for the file from the fileNamesList.
Thank you for taking the time to look at this.
First Code:
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
fCount = 0
For i = 0 To fileNames.Count() - 1
Dim fileName = fileNames(i)
'sFileToFind = location & "\" & fileName & "*.*"
Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
If Not paths.Any() Then
System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
Else
For Each pathAndFileName As String In paths
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", sRegLast)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder, True)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
fileFilename = (fileName) + vbCrLf
fCount = fCount + 1
BackgroundWorker1.ReportProgress(fCount)
'fileCount.Text = fCount
End If
End If
Next
End If
BackgroundWorker1.ReportProgress(100 * i / fileNames.Count())
'statusText = i & " of " & fileName.Count() & " copied"
fCount = i
Next
Second Code:
FILE_NAME = txtFileName.Text 'textfield with lines of filenames are located ]
Dim fileNamesList = System.IO.File.ReadAllLines(FILE_NAME)
location = txtFolderPath.Text
fCount = 0
' Two list to collect missing and found files
Dim foundFiles As List(Of String) = New List(Of String)()
Dim notfoundFiles As List(Of String) = New List(Of String)()
Dim fileNames As String() = System.IO.Directory.GetFiles(createXMLFldr)
For Each file As String In fileNamesList
Debug.Write("single file : " & file & vbCr)
' Check if the files is contained or not in the request list
Dim paths = IO.Directory.GetFiles(location, file, IO.SearchOption.AllDirectories)
If fileNamesList.Contains(Path.GetFileNameWithoutExtension(file)) Then
Dim FileNameOnly = Path.GetFileName(file)
Debug.Write("FileNameOnly " & FileNameOnly & vbCr)
If System.IO.File.Exists(FileNameOnly) = True Then
'if toFileLoc = XML file exists move it into the XML files folder
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", file)
foundFiles.Add(file) 'add to foundFiles list
fileFilename = (file) + vbCrLf 'add file name to listbox
fCount = fCount + 1
Else
notfoundFiles.Add(file)
End If
End If
Next
File.WriteAllLines(ListofFiles, foundFiles)
File.WriteAllLines(orphanedFiles, notfoundFiles)
This is just a starting point for you, but give it a try:
Friend Module Main
Public Sub Main()
Dim oFiles As List(Of String)
Dim _
sOrphanedFiles,
sSearchFolder,
sFoundFiles,
sTargetFile As String
sOrphanedFiles = "D:\Results\OrphanedFiles.txt"
sSearchFolder = "D:\Files"
sFoundFiles = "D:\Results\FoundFiles.txt"
oFiles = IO.File.ReadAllLines("D:\List.txt").ToList
oFiles.ForEach(Sub(File)
If IO.Directory.GetFiles(sSearchFolder, File, IO.SearchOption.AllDirectories).Any Then
sTargetFile = sFoundFiles
Else
sTargetFile = sOrphanedFiles
End If
IO.File.AppendAllText(sTargetFile, $"{File}{Environment.NewLine}")
End Sub)
End Sub
End Module
If I've misjudged the requirements, let me know and I'll update accordingly.
Explanations and comments in-line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'I presume txtFileName.Text contains the full path including the file name
'I also presume that this text file contains only file names with extensions
Dim FilesInTextFile = System.IO.File.ReadAllLines(txtFileName.Text)
'Instead of accessing the Directory over and over, just get an array of all the files into memory
'This should be faster than searching the Directory structure one by one
'Replace <DirectoryPathToSearch> with the actual path of the Directory you want to search
Dim FilesInDirectory = IO.Directory.GetFiles("<DirectoryPathToSearch>", "*.*", IO.SearchOption.AllDirectories)
'We now have an array of full path and file names but we just need the file name for comparison
Dim FileNamesInDirectory = From p In FilesInDirectory
Select Path.GetFileName(p)
'A string builder is more efficient than reassigning a string with &= because a
'string build is mutable
Dim sbFound As New StringBuilder
Dim sbOrphan As New StringBuilder
'Instead of opening a file, writing to the file and closing the file
'in the loop, just append to the string builder
For Each f In FilesInTextFile
If FileNamesInDirectory.Contains(f) Then
sbFound.AppendLine(f)
Else
sbOrphan.AppendLine(f)
End If
Next
'After the loop write to the files just once.
'Replace the file path with the actual path you want to use
IO.File.AppendAllText("C:\FoundFiles.txt", sbFound.ToString)
IO.File.AppendAllText("C:\OrphanFiles.txt", sbOrphan.ToString)
End Sub

Create a vb class using a text file. The values for class name and attributes should come from database

I want to create an executable that will use a text file as a template and create a class in vb.net
The class name and its attributes are stored in the database. The user should be able to input the class name. The ClassName and AttributeName tags in the template are to be replaced by the corresponding values from the database.
Any lead would be appreciated. Thank You.
Code files are just text files. Generating code files is a bit confusing because you have source code appearing as string literals, but in a technical sense it isn't very difficult:
Sub GenerateCode()
Dim dtb As New DataTable
dtb.Columns.Add("ClassName")
dtb.Columns.Add("PropertyName")
dtb.Columns.Add("PropertyType")
'NOTE: datatable must be sorted by ClassName
dtb.Rows.Add("ClassOne", "PropertyOne", "String")
dtb.Rows.Add("ClassOne", "PropertyTwo", "Integer")
dtb.Rows.Add("ClassOne", "PropertyThree", "String")
dtb.Rows.Add("ClassTwo", "AnotherPropertyOne", "String")
dtb.Rows.Add("ClassTwo", "AnotherPropertyTwo", "Integer")
dtb.Rows.Add("ClassTwo", "AnotherPropertyThree", "String")
Dim strFilename As String = ""
Dim strParentFolder As String = "C:\Junk"
If Not System.IO.Directory.Exists(strParentFolder) Then
System.IO.Directory.CreateDirectory(strParentFolder)
End If
Dim strPreviousClassName As String = ""
Dim sb As New System.Text.StringBuilder
For Each drwProperty As DataRow In dtb.Rows
Dim strThisClassName As String = drwProperty("ClassName").ToString
If strThisClassName <> strPreviousClassName Then
'class name has changed
If strPreviousClassName > "" Then
'write previous class
sb.AppendLine("End Class")
strFilename = strParentFolder & "\" & strPreviousClassName & ".vb"
My.Computer.FileSystem.WriteAllText(strFilename, sb.ToString, False)
End If
'start new class
sb = New System.Text.StringBuilder
sb.AppendLine("Class " & strThisClassName)
strPreviousClassName = strThisClassName
End If
'append property
sb.AppendLine(" Property " & drwProperty("PropertyName").ToString & " As " & drwProperty("PropertyType").ToString)
Next drwProperty
'Write last class
sb.AppendLine("End Class")
strFilename = strParentFolder & "\" & strPreviousClassName & ".vb"
My.Computer.FileSystem.WriteAllText(strFilename, sb.ToString, False)
End Sub

Find a line by searching for a string, then edit a line which is 2 lines below

My first question here, I'll try to be as clear as possible.
I have a text file that looks like this :
[...]
"tickets"
{
"436" "320000000400000083421a060100100104"
"674" "320000000400000083421a06010010010a"
"292" "320000000400000083421a0601001001f0"
"551" "320000000400000083421a0601001001da"
}
"99550"
{
"informations" "254"
"parameters" "-banana -lemon"
}
"99551"
{
"informations" "641"
"parameters" "-banana -lemon"
}
"550"
{
"informations" "551"
"parameters" "-banana -lemon"
}
"551"
{
"informations" "123"
"parameters" "-banana -lemon"
}
"552"
{
"informations" "987"
"parameters" "-banana -lemon"
}
[...]
What I want to do is:
search for this string in the text file :
"551"
{
add -apple to the parameters line which is 2 lines below, should look like this :
"parameters" "-banana -lemon -apple"
I think it's the only way to find this line, but I don't get the coding skills to get it done.
You can try something like this:
Function ReplaceSpecial(ByVal text As String, ByVal find As String, ByVal insert As String) As String
Dim allLines() As String = Split(text, vbCrLf)
Dim lineNumber = Array.IndexOf(allLines, find)
Dim lineToUpdate = Array.FindIndex(Of String)(allLines, lineNumber, Function(f) f.Trim.StartsWith("""parameters"""))
allLines(lineToUpdate) = allLines(lineToUpdate).Trim.Substring(0, allLines(lineToUpdate).Length - 1) & " " & insert & """"
Return Join(allLines, vbCrLf)
End Function
Sample Usage:
Assuming that your input text is in a textbox named InputTextBox the following code will show you updated text in OutputTextBox.
OutputTextBox.Text = ReplaceSpecial(InputTextBox.text, """550""", "-apple")
Here's another one, not much different than Pradeep Kumar's submission:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = "C:\Users\Mike\Documents\SomeFile.txt"
Dim lines As New List(Of String)(File.ReadAllLines(FileName))
AddParameterToSection(lines, "551", "-apple")
AddParameterToSection(lines, "552", "-orange")
File.WriteAllLines(FileName, lines)
End Sub
Private Sub AddParameterToSection(ByVal lines As List(Of String), ByVal sectionID As String, ByVal parameter As String)
Static DoubleQuote As String = Chr(34)
Static Parameters As String = DoubleQuote & "parameters" & DoubleQuote
Static PairOfDoubleQoutes As String = DoubleQuote & DoubleQuote
Dim header As String = DoubleQuote & sectionID & DoubleQuote
Dim index As Integer = lines.FindIndex(Function(x) x.Trim() = header)
If index <> -1 Then
Dim endBracket As Integer = lines.FindIndex(index, Function(x) x.Trim() = "}")
Dim paramIndex As Integer = lines.FindIndex(index, Function(x) x.Trim().StartsWith(Parameters))
If paramIndex <> -1 AndAlso paramIndex < endBracket Then
If lines(paramIndex).EndsWith(PairOfDoubleQoutes) Then
lines(paramIndex) = lines(paramIndex).Replace(PairOfDoubleQoutes, DoubleQuote & parameter & DoubleQuote)
Else
lines(paramIndex) = lines(paramIndex).TrimEnd(DoubleQuote) & " " & parameter & DoubleQuote
End If
End If
End If
End Sub

VB.net lag across different machines

I wrote a small little key inventory program. Basically it uses an INI file to know what keys we have and which ones are signed out, to whom, by whom, etc. It is run on up to 4 computers all in the same room and accesses the ini file on our local server.
When I sign a key out or in, it shows the change instantly. If I run two instances of the same program on the same machine, again, it's instant.
When I sign out a key on machine A and a co-worker is running the same program on machine B, C or D, the change in what is signed out doesn't show up for 4-10 seconds.
The way the program checks for updates is by using IO.File.Getlastwritetime on loading (saving it to a label with visible = false) and then every time the timer goes (every second) it compares the files "getlastwritetime" to the label. If they are different, then it updates, if they are the same, it does nothing.
Any idea where I should start looking for this lag? Could it be a server problem?
Here is the code for Timer1.tick, I am using the read/write ini codes from http://deepvbnet.blogspot.in/2008/07/how-to-read-from-ini-file.html
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim TimeCheck As String = IO.File.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/keys.ini")
If TimeCheck <> Label5.Text Then
ListBox1.Items.Clear()
ComboBox1.Items.Clear()
str1 = "NumOfKeys"
Call readIniFile()
Dim OneTime As String = strdata.ToString
Dim numberofkeys As Integer = Convert.ToInt32(OneTime)
For i = 1 To numberofkeys
str1 = "Key" & i & "Out"
Call readIniFile()
Dim isKeyOut As String = strdata.ToString
If isKeyOut = "True" Then
str1 = "Key" & i & "Name"
Call readIniFile()
Dim KeyName As String = strdata.ToString
str1 = "Key" & i & "Unit"
Call readIniFile()
Dim string1 As String = strdata.ToString
str1 = "Key" & i & "Rent"
Call readIniFile()
Dim string2 As String = strdata.ToString
str1 = "Key" & i & "User"
Call readIniFile()
Dim string3 As String = strdata.ToString
str1 = "Key" & i & "Date"
Call readIniFile()
Dim string4 As String = strdata.ToString
str1 = "Key" & i & "Time"
Call readIniFile()
Dim string5 As String = strdata.ToString
ListBox1.Items.Add(LSet(KeyName, 20) + " - " + string1 + " - " + string2 + " - " + string3 + " - " + string4 + " - " + string5)
ElseIf isKeyOut = "False" Then
str1 = "Key" & i & "Name"
Call readIniFile()
Dim thisKeysName As String = strdata.ToString
ComboBox1.Items.Add(thisKeysName)
End If
Next
Dim FileTime As String = IO.File.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/keys.ini")
Label5.Text = FileTime
End If
Dim escortTime As String = IO.Directory.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/Escort")
If escortTime <> Label7.Text Then
ListBox2.Items.Clear()
For Each foundfile In My.Computer.FileSystem.GetFiles("G:/BFAS/DPS/Comm Center/TEST/Escort/")
If foundfile = "G:/BFAS/DPS/Comm Center/TEST/Escorthistory.txt" Then
'do nothing
Else
Dim Infomation As String = My.Computer.FileSystem.ReadAllText(foundfile)
ListBox2.Items.Add(Infomation)
End If
Next
Label7.Text = IO.Directory.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/Escort")
End If
Dim alarmtime As String = IO.Directory.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/Alarms")
If alarmtime <> Label8.Text Then
ListBox3.Items.Clear()
For Each foundfile In My.Computer.FileSystem.GetFiles("G:/BFAS/DPS/Comm Center/TEST/Alarms/")
Dim Infomation As String = My.Computer.FileSystem.ReadAllText(foundfile)
ListBox3.Items.Add(Infomation)
Next
Label8.Text = IO.Directory.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/Alarms")
End If
Dim turnovertime As String = IO.File.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/turnover.txt")
If Label9.Text <> turnovertime Then
Dim newTO As String = My.Computer.FileSystem.ReadAllText("G:/BFAS/DPS/Comm Center/TEST/turnover.txt")
TextBox3.Text = newTO
Label9.Text = IO.File.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/turnover.txt")
End If
End Sub

Path not found when creating a file-VBA

I'm trying to create a text file and write data to it, simple right.
Well it's not working and I've looked everywhere for it but can't find an answer.
When it gets to the CreateTextFile() method it throws a path not found error. But I've made sure the path is valid and exists.
'Create a text file
Private Sub OpenFile()
Dim filePath As String
Dim fileName As String
Dim fullPath As String
Const ForAppending = 8, TristateFalse = 0
Dim curDate As Date
Dim strDate As String
curDate = Date
strDate = CStr(curDate)
fileName = "DCSSInputLitigation_" & "(" & strDate & ")" & ".txt"
filePath = "C:\TempFolder\"
Set fs = CreateObject("Scripting.FileSystemObject")
fullPath = fs.BuildPath(filePath, fileName)
Set fWriter = fs.CreateTextFile(fullPath)
End Sub
When I hard code the path in the method it works but not when I use variables. Any Ideas?
Set fWriter = fs.CreateTextFile("C:\TempFolder\test.txt")
When you get the date as follows:
strDate = CStr(curDate)
you are adding / into the file name and the string value for fullPath which you create is:
C:\TempFolder\DCSSInputLitigation_(6/12/2014).txt
File names cannot have / in them on Windows so you are running into problems here.
You can either format the date or replace the / like:
strDate = replace(CStr(curDate),"/","-")
strDate = Format(curDate,"dd-mm-yyyy")
Either will work.