Create a text file with a variable name and write to it - vb.net

For an application i'm working on, i am trying to create a 'save data' feature.
First off, it needs to create a .txt file with a custom name, this needs to be the date (today) and the text of a textbox, it needs to be in the format of yyyymmdd_textbox1(.txt)
How would i go about doing this? it can create it where ever, but if it already exists it needs to append to it on a new line
thanks for any responses

If you want a file-name from user-input you first need this method:
Public Function SanitizeFileName(fileName as String) As String
For Each c In IO.Path.GetInvalidFileNameChars()
filename = filename.Replace(c, "_"c)
Next
Return fileName
End Function
Then it's easy
Dim filename = $"{DateTime.Today.ToString("yyyyMMdd")}_{SanitizeFileName(textbox1.Text)}.txt"

Related

How to Auto Copy text file from one folder to another folder in vb 2010 console or windows application

I want to create a program that auto copy text file from one folder to another folder . is it possible to make in windows form in vb.net ? if not what about in console apps ? i tried to search but i didn't find an answer for both. please help me i'm new to to this. I want to copy all the text file that is being save to c:folder1\test1.text copy to c:folder2\test1.text then test2.text,test3.text all the text file that are being put in folder1. i want to copy in folder2.
now i only have this code:
it will only copy 1 specific textfile with file name test.txt.
enter code here
My.Computer.FileSystem.CopyFile("C:\CopyTo\test.txt",
"C:\CopyHere\test.txt")
Of course! First of all we need a function that search for files.
Public Sub SearchFiles(ByVal Pattern As String, ByVal Path As String, ByVal FilesFound As ArrayList)
FilesFound.AddRange(Directory.GetFiles(Path, Pattern))
End Sub
But where we should save the list of files? We can use a Array for it. Also we should define our output and input folder
Dim files As New ArrayList
Dim inDir As String = "input path"
Dim outDir As String = "output path"
We can now call this function like this:
SearchFiles("*.txt", inDir, files)
All .txt files in the folder are now saved in our Array List. But how we can work with it? We can now work with it like this:
Try
For Each file As String In files
Dim fName As String = Path.GetFileName(file)
My.Computer.FileSystem.CopyFile(file , outDir & "\" & fName, overwrite:=False)
Next
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
This will copy every .txt file that where found in our inDir to our outDir. If something goes wrong then you will see this in the console. Try it out and understand how it works :)

How do I search multiple textfiles for text, then adding that text into a listbox

I've got multiple text files within a folder, like this:
C:\Example\ 1.txt, 2.txt, 3.txt, 4.txt
The file names are generated by time and date they were created at so please don't try to open/search the documents using [1-4].txt or something similar as these are just examples.
I would like to search through all of these text files (without knowing their names as they're randomly generated), and if it matches certain text, I would like the rest of the text on that line to be added into a ListBox, then search the next/rest of the text files.
Example of text file contents:
[14:49:16] [Client thread/INFO]: Setting user: Users Name
All text after Setting user: which is on the same line should be added to the ListBox, so in this case, Users Name would be added.
The above text will always be the first line of the text file, so no need to search the whole file, the beginning of the text will always be the time created at (which will be different for each text file), then followed by [Client thread/INFO]: Setting user: which will always be the same for all of the text files, then Users Name , which wont actually output Users Name, this is what I would like to find, and then add to the ListBox.
I've got some of the code created, but there's three problems with it.
1: I have to define the name of the text file, which I will not know.
2: I'm not sure how to search through all of the documents, only the one that is defined.
3: I can get it to output the Users name, but only if I remove the leading time and [Client thread/INFO]:, but these items will always be there.
With these three problems, the code is useless, I'm just providing it as possibly it will make it easier for someone to help me?
Public Class Form1
Private Sub LoadFiles()
For Each line As String In IO.File.ReadLines("C:\Example\2016-09-28-1.txt")
'I had to define the name of the text file here, but I need to somehow automatically
'search all .txt files in that folder.
Dim params() As String = Split(line, ": ")
Select Case params(0)
'Text file has to be modified to show as:
Setting user: RandomNameHere
'for the RandomName to show within the ListBox,
'but normally it will never be shown like this within the text files.
Case "Setting user"
ListBox1.Items.Add(params(1))
End Select
Next
End Sub
Use System.IO.Directory.GetFiles to get the list of files, and System.IO.Path.GetExtension to filter for .txt files. The String.IndexOf function will let you search for text within each line of the file, and String.Substring will let you retrieve part of the line.
While your original code using Split could be made to work (you would need another loop to go through the split text), I think IndexOf and Substring are simpler in this case.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strFilenames() As String = System.IO.Directory.GetFiles("C:\Example")
For i As Integer = 0 To strFilenames.GetUpperBound(0)
Dim strFilename As String = strFilenames(i)
If System.IO.Path.GetExtension(strFilename).ToLower = ".txt" Then
For Each strLine As String In System.IO.File.ReadLines(strFilename)
'[14:49:16] [Client thread/INFO]: Setting user: Users Name
Dim strSearchText As String = "Setting user: "
Dim intPos As Integer = strLine.IndexOf(strSearchText)
If intPos > -1 Then
Dim strUsername As String = strLine.Substring(intPos + strSearchText.Length)
MsgBox(strFilename & " - " & strUsername) '<-- replace this with your SELECT CASE or whatever
End If
Next strLine
End If
Next i
End Sub
You can use system.io.directory class and use the getfiles method to get the filenames from a directoy. then you can open the file and do the needful.
https://msdn.microsoft.com/en-us/library/system.io.directory.getfiles(v=vs.110).aspx

VB.net FileSystem.rename - old path knowing only a substring

How can I rename a file that I don't know the full name, but I only know that it begin with a base string?
I must rename a file in a folder, that begins with a default string and then has extra unknow chars. I'm sure in that folder will be only one file beginning with that string.
It would be something like searching "string*.txt" and rename it with "string.txt", but FileSystem.rename doesn't accept oldPath with "*" as argument.
Dim _files as String() = IO.Directory.GetFiles("c:\temp\", "string*.txt")
IO.File.Move(_files(0), "c:\temp\newfilename.txt")
Still needs some checking if file found, etc. but this should work
You need to loop through all the files in your given directory, if one name matches then you know it's your file.
Structure of the code might look like this :
Function LookForName(Path As String) As String
'For Each File in your path
'If the name starts with "string" and ends with ".txt"
'You can return this filename
End Function
'You call LookForName with a given path
'You rename the returned file

How to search data in a txt file through Visual Basic

I have this txt file with the following information:
National_Insurence_Number;Name;Surname;Hours_Worked;Price_Per_Hour so:
eg.: aa-12-34-56-a;Peter;Smith;36;12
This data has been inputed to the txt file through a VB form which works totally fine, the problem comes when, on another form. This is what I expect it to do:
The user will input into a text box the employees NI Number.
The program will then search through the file that NI Number and, if found;
It will fill in the appropriate text boxes with its data.
(Then the program calculates tax and national insurance which i got working fine)
So basically the problem comes telling the program to search that NI number and introduce each ";" delimited field into its corresponding text box.
Thanks for all.
You just need to parse the file like a csv, you can use Microsoft.VisualBasic.FileIO.TextFieldParser to do this or you can use CSVHelper - https://github.com/JoshClose/CsvHelper
I've used csv helper in the past and it works great, it allows you to create a class with the structure of the records in your data file then imports the data into a list of these for searching.
You can look here for more info on TextFieldParser if you want to go that way -
Parse Delimited CSV in .NET
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(FileName)
Dim CurrentRecord As String() ' this array will hold each line of data
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {";"}
afile.HasFieldsEnclosedInQuotes = True
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
I'd recommend using CsvHelper though, the documentation is pretty good and working with objects is much easier opposed to the raw string data.
Once you have found the record you can then manually set the text of each text box on your form or use a bindingsource.

write content to notepad in specified format with separator

i want to create a notepad in this format
100001|10001|1001|91|9942321400|MR|Hari|Q|PUBLIC|249 MUNDON ROAD|MALDON|FL|44|TN|NO_PROVINCE|600004|IN|M|27304|9942321400|test#test.com|nothing|COMMENTS|1|Southeast
100001|10001|1001|91|9865015695|MR|Hari|Q|PUBLIC|249 MUNDON ROAD|MALDON|FL|44|TN|NO_PROVINCE|600004|IN|M|27304|9942321400|test#test.com|nothing|COMMENTS|1|Southeast
100001|10001|1001|91|9894825469|MR|Hari|Q|PUBLIC|249 MUNDON ROAD|MALDON|FL|44|TN|NO_PROVINCE|600004|IN|M|27304|9942321400|test#test.com|nothing|COMMENTS|1|Southeast
am using vb.net,in the above format except phone number remaining values are same.and it would be written in to the notepad with pipeline separator.
phone number values are recieved from dataset and store it in a variable . with in looping am use stream writer statement. but am not able to get the output. please help me to do this? am new to vb.net
Try something like that to write your file.
Import System.IO and add that routine. The Path should be the complete path including the file name and extension of the file you want to generate. If you change False to True it will append the text at the final of the file if you write it again, with false it overwrite it.
Using writer As StreamWriter = New StreamWriter(path, False, System.Text.Encoding.UTF8)
for each ...
writer.writeLine(var1+"|"+var2...)
Next
writer.Close()
End Using