I have written a basic console application and I want to write the data entered to a .csv file
When I enter test data the execution of the module is fine but it does not write to the .csv
I am trying to create an automated test data generation and this is my first attempt at vb by writing to .csv.
I want the code to pop up an input screen where data is input and written to a.csv file , the pop up is fine but the .csv is blank
Code. I have:
Module Module1
Dim objFile As New System.IO.StreamWriter("C:\Users\User\Documents\test.csv.csv", True)
Sub Main()
Console.WriteLine("what is your name")
Console.ReadLine()
Console.WriteLine("What is your Age")
Console.ReadLine()
Console.WriteLine("What is your Your Group")
Console.ReadLine()
End Sub
End Module
Here is the code I believe you are looking for. There are some pretty basic concepts that you appear to be missing (like storing values in variables and accessing those variables later). This sample demonstrates how to perform the task you described, but isn't useful in any practical sense.
Module Module1
Sub Main()
Console.WriteLine("What is your name?")
Dim Name As String = Console.ReadLine()
Console.WriteLine("What is your age?")
Dim Age As String = Console.ReadLine()
Console.WriteLine("What is your group?")
Dim Group As String = Console.ReadLine()
Using sw As New System.IO.StreamWriter("c:\test\outputfile.csv")
sw.WriteLine(Name & "," & Age & "," & Group)
End Using
End Sub
End Module
Related
I am trying to figure out how to move 5 files
settings.txt
settings2.txt
settings3.txt
settings4.txt
settings5.txt
from one folder to another.
Although I know what the file names will be and what folder Name they will be in, I don't know where that folder will be on the Users computer.
My thought process is to use a FolderBrowseDialog which the user can browse to where the Folder is, and then when OK is pressed, it will perform the File copy to the destination folder, overwriting what's there.
This is what I have so far.
Dim FolderPath As String
Dim result As Windows.Forms.DialogResult = FolderBrowserImport.ShowDialog()
If result = DialogResult.OK Then
FolderPath = FolderBrowserImport.SelectedPath & "\"
My.Computer.FileSystem.CopyFile(
FolderPath & "settings.txt", "c:\test\settings.txt", overwrite:=True)
ElseIf result = DialogResult.Cancel Then
Exit Sub
End If
Rather than run this 5 times, is there a way where it can copy all 5 files at once
I know why IdleMind recommended the approach they did, but it would probably make for a bit more readable code to just list out the file names:
Imports System.IO
...
Dim result = FolderBrowserImport.ShowDialog()
If result <> DialogResult.OK Then Exit Sub
For Each s as String in {"settings.txt", "settings2.txt", "settings3.txt", "settings4.txt", "settings5.txt" }
File.Copy( _
Path.Combine(FolderBrowserImport.SelectedPath, s), _
Path.Combine("c:\test", s), _
True _
)
Next s
You can swap this fixed array out for a list that VB prepares for you:
For Each s as String in Directory.GetFiles(FolderBrowserImport.SelectedPath, "settings*.txt", SearchOption.TopDirectoryOnly)
File.Copy(s, Path.Combine("c:\test", Path.GetFilename(s)), True)
Next s
Tips:
It's usually cleaner to do a If bad Then Exit Sub than a If good Then (big load of indented code) End If - test all your known failure conditions at the start and exit the sub if anything fails, rather than arranging a huge amount of indented code
Use Path.Combine to combine path and filenames etc; it knows how to deal with stray \ characters
Use Imports to import namespaces rather than spelling everything out all the time (System.Windows.Forms.DialogResult - a winforms app will probably have all the necessaries imported already in the partial class so you can just say DialogResult. If you get a red wiggly line, point to the adjacent lightbulb and choose to import System.WIndows/Forms etc)
Once you have the selected folder, use a For loop to build up the names of the files you're looking for. Use System.IO.File.Exists() to see if they are there. Use System.IO.Path.Combine() to properly combine your folders with the filenames.
Here's a full example (without exception handling, which should be added):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FolderBrowserImport.ShowDialog() = DialogResult.OK Then
Dim FolderPath As String = FolderBrowserImport.SelectedPath
For i As Integer = 1 To 5
Dim FileName As String = "settings" & If(i = 1, "", i) & ".txt"
Dim FullPathFileName As String = System.IO.Path.Combine(FolderPath, FileName)
If System.IO.File.Exists(FullPathFileName) Then
Dim DestinationFullPathFileName = System.IO.Path.Combine("c:\test", FileName)
My.Computer.FileSystem.CopyFile(FullPathFileName, DestinationFullPathFileName, True)
Else
' possibly do something in here if the file does not exist?
MessageBox.Show("File not found: " & FullPathFileName)
End If
Next
End If
End Sub
Ok so, I have all my program and what not, it's just I don't how to prevent it from quitting the program after the execution of a
private sub
Like for example, I have
Private Sub KeyList()
Console.WriteLine("1.) File - Opens a test file")
Console.WriteLine("2.) Update - Updates the program using an external .bat file")
Console.WriteLine("3.) Username - ReDo Your username")
Console.WriteLine("4.) Site - Starts your browser and leads you to our site :D")
Console.WriteLine("5.) PLUGIN_STRT_NOPROT - Starts the loaded plugin without layered protection, do not do this unless you know")
Console.WriteLine("what you are doing")
Console.WriteLine("6.) PLUGIN_STRT_PROT - Starts loaded plugin with protection, reccomended.")
Console.WriteLine("7.) API_Str_Rand - Creates a random API string that you can assign to a plugin.")
Console.WriteLine("8) DownloadDevKit - Downloads the developmental kit to create a plugin")
End Sub
but after I hit any other key, the program terminates. How do I prevent the program from terminating, and going back to the
sub main()
Here is my data code for the entire program, it's VB.net 2010.
Module Module1
Sub Main()
REM Add all the Dimensions/Descriptions here.
Dim VersionName As String = "1"
Dim Action As String = "Action"
Dim username As String = "UserName"
REM The Visual part of the program. No pun intended :>
REM Ask the name for the session.
username:
Console.WriteLine("Hello, What is your name? ")
username = Console.ReadLine()
Console.WriteLine("Hello " + username)
If username = "Skycoder" Then
Console.WriteLine("Welcome back!, Planned updates to include in this are, 1.) ADd in more key features")
Console.WriteLine("2.) Add hotkeys")
Console.WriteLine("3.) Implement and auto updater")
Console.Beep()
If username = "" Then
Console.WriteLine("Please type in name. Numerals can be used")
GoTo username
End If
End If
Fish:
Console.ReadLine()
Console.Clear()
Console.Title = ("Desktop TBI | Hello " + username)
Console.WriteLine("-----------------------------------------------------------------------------------------------------------")
Console.WriteLine("Please select an option, note that this is a work in progress, and will contain more features in the future")
Console.WriteLine("")
Console.WriteLine(" Type 'File' to create the directory (Important if you want to add plugins)")
Console.WriteLine(" Using Version: " + VersionName)
Console.WriteLine("-----------------------------------------------------------------------------------------------------------")
Console.WriteLine(" Please choose what action you want to do")
Console.WriteLine(" Type in 'File' To find the directory")
Console.WriteLine(" Type in 'Update' To open the .bat file to download the updates")
Console.WriteLine("-----------------------------------------------------------------------------------------------------------")
Console.WriteLine("To create the new path, enter 'CreateDir'")
REM Begin the part where users can select their code.
Dim selection As String = Console.ReadLine
Select Case selection
REM This allows the creation of a text file.
Case "File"
Console.Clear()
File() REM Private sub selection
REM Updates their program.
Case "Username"
Console.Clear()
GoTo UserName
REM Set's their username for the program.
Case "Update"
Update()
Case "KeyList"
KeyList()
Case "CreateDir"
CreateDir()
Case "SERV_Start"
Chat_Start_SERV()
Case "Site"
Site()
Console.ReadLine()
End Select
End Sub
but after I select the case that I want to use and head into the sub code for the
keylists, it just terminates, and it doesn't even wait for me to read it. I'll literally provide video of it happening if it helps anyone... I am desperate...
Put your Select case block in the loop, add one more option ("Exit" for example) - if that option will be selected exit loop and application will be exited.
Console.WriteLine("0) Exit - Exit application")
Dim selection As String = Console.ReadLine()
While selection.Equals("Exit") = false
Select Case selection
REM This allows the creation of a text file.
Case "File"
Console.Clear()
File() REM Private sub selection
'...
'... other Case values
'...
End Select
selection = Console.ReadLine()
Loop
This application will only hit the Console.ReadLine() if the user entered "Site". Move the Readline statement below the End Select statement and it will do what you want.
I am trying to get my application to show data from a text file to a list box with visual basics. I have it working for small sized text files no problem, but it will not work for text files the size of say 20mb. Is there any reason why it wouldn't load such or maybe some kind of limitations?
I forgot to ask, could it possibly just a matter of having to wait a long time? The program just sits there and I can't interact with it while it's getting the data...I think anyway....
Sub OpenFiles()
Dim myName As String = Dir(downloadTo + "*.TXT")
Do While myName <> ""
lstFiles.Items.Add(myName)
myName = Dir()
Loop
End Sub
Sub ReadFiles(textFile As String)
Dim logReader As New System.IO.StreamReader(textFile)
lstSrchTxt.Items.Clear()
While logReader.EndOfStream <> True
Dim stringx As String = logReader.ReadLine
If stringx.Contains(searchText) Then
lstSrchTxt.Items.Add(stringx)
End If
End While
logReader.Close()
End Sub
The issue was that I was entering too much data and it needed time to process all of the characters.
I have the following code that I am using to parse out a test file. I am getting variable conversion error in Sub Main() when I assign file = Read(). The return value of Read() is a TextFieldParser type. How do I assign the proper variable type to "file" so I can write the output to a text file?
Thanks!
Module Module1
Function Read()
Using MyReader As New FileIO.TextFieldParser("C:\Users\Colin\Desktop\Parse_Me.txt")
Dim currentRow As String
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadLine()
Console.WriteLine(Parse_me(currentRow))
Catch ex As FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
" is invalid. Skipping")
End Try
End While
Return MyReader
MyReader.Close()
End Using
End Function
Function Parse_me(ByVal test As String)
Dim Set_1, Set_2, Set_3, Set_4, Set_5 As String
Dim new_string As String
Set_1 = test.Substring(0, 4)
Set_2 = test.Substring(7, 2)
Set_3 = test.Substring(11, 1)
Set_4 = test.Substring(14, 4)
Set_5 = test.Substring(20, 4)
new_string = Set_1 & " " & Set_2 & " " & Set_3 & " " & Set_4 & " " & Set_5
Return new_string
End Function
Sub Main()
Dim file As Object
file = Read()
FilePutObject("C:\Users\Colin\Desktop\Parse_Meoutput.txt", file)
End Sub
End Module
Here's how FilePutObject is supposed to work (example taken from MSDN documentation for FilePutObject):
Sub WriteData()
Dim text As String = "test"
FileOpen(1, "test.bin", OpenMode.Binary)
FilePutObject(1, text)
FileClose(1)
End Sub
The 1 act as an identifier for the file. Note also that the file name is passed to FileOpen before calling FilePutObject, and that FileClose is called afterwards. Also note that a string is being written to the file. I don't know which types of data are valid for being passed to FilePutObject, but FileIO.TextFieldParser is definitely not one of them (I just tried it).
Correct me if I'm wrong, but I'm pretty sure that FilePutObject is one of those carry-overs from VB6. If you're writing new code, I would rather use a Stream object for my I/O. For one, it's a lot more .Net-ish (i.e., type-safe, object-oriented, etc). And as far as usability goes, it's a lot clearer how a Stream works, not to mention it doesn't involve passing arbitrary integers as handles to functions in order to identify which file you'd like to work with. And to top it all off, a Stream works whether you want to write to a file, to the console, or send the data to another machine. To sum up, I would definitely look up the Stream class, some of its child classes (like FileStream, and whatever else appeals to you), and some associated types (such as the TextWriter class for conveniently writing text).
Change the definition of the function "read" to:
Function Read() as FileIO.TextFieldParser
and change the declaration of "file" in sub main to:
Dim file as FileIO.TextFieldParser
That way the data type of the function and assignment match.
I am assuming there is a way to have this sub in? I am assuming Do Until Loop is the way to go, I just do not know how to contruct one.
Sub Main()
'Declare Command
Dim sCommand As String
'Declare File where Users are Located
Dim strFile As String = "C:\TestDUsers.txt"
'Running from Admin Comptuer so permissions are fine
'Want to replace the ******** section with each username from text file
sCommand = "pushd \\*********\C$ && whoami.exe >> C:\File.txt"
'Load the File and perform the loop????
Using sr As New StreamReader(File.Open(strFile, FileMode.Open))
End Using
Console.WriteLine()
Console.Clear()
End Sub
Something like this if I understand your question correct:
Sub Main()
HandleJavaInfo()
End Sub
Sub HandleJavaInfo()
Dim strFile As String = "C:\Users\pseal2\Desktop\TestDUsers.txt"
Dim strCommand = "pushd \\*********\C$ && whoami.exe >> C:\Users\pseal2\Desktop\Javainfo."
Dim strLines() As String = IO.File.ReadAllLines(strFile)
For Each strUserName As String In strLines
'execute the command as shell or process
'Example using Shell (run the command whitout showing the window for the user)
Dim ThisCommand As String = strCommand.Replace("*********", strUserName)
Shell(ThisCommand, AppWinStyle.Hide)
'Example using process
Process.Start("pushd", "\\" & strUserName & "\C$ && whoami.exe >> C:\Users\pseal2\Desktop\Javainfo.")
Next
End Sub
Now, you have only told us what you want to DO, not what you want to achieve. If you tell us exactly what the goal is, then it may be some other .Net ways to do what you want, instead of shelling out to a DOS-command, and you can get more accurate answers.