code that doesn't work...Kill-process , search-for-file , streamwrite on file searched file - vb.net

can you help me with that code ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As String = "C:\Users\Andy\Documents\Visual Studio 2008\Projects\minecraft srv\"
For Each app As Process In Process.GetProcesses
If app.ProcessName = "notepad" Then
app.Kill()
End If
Next
Dim result As String
Dim servprop() As String
servprop = System.IO.Directory.GetFiles(x, "server.*")
For Each file In servprop
result = Path.GetFileName(file)
Next
Dim z As String = "C:\Users\Andy\Documents\Visual Studio 2008\Projects\minecraft srv\" & result.ToString
Dim t As StreamWriter = New StreamWriter(z)
t.WriteLine(TextBox1.Text.ToString)
t.Close()
End Sub
so... I got a button (button1) that finds if notepad is opened and kills it.
Then it searches for "server.Properties" in "x" location
if server.properties is found , then "result" will get his name (server)
"z" is the file location where streamwriter must write the text from textbox1 .
And it doesn't work... streamwirter is not writing on server.properties ... why ?
mention : I'm just a kid :D and i'm trying to learn by myself visual basic .

If you have only one file called "server.properties" then you could remove all the code that search for this file and write it directly.
Dim z As String
z = System.IO.Path.Combine(x, "server.properties")
Using t = New StreamWriter(z)
t.WriteLine(TextBox1.Text.ToString)
t.Flush()
End Using
Regarding the error, encapsulating the writing code with a proper using statement ensures a complete clean-up. Also adding a call to Flush() is probably not necessary, but doesn't hurt.

Related

Saving a Structure to a Binary File

I am creating an application using a windows forms application in visual studio in the vb.net language. I need help converting a structure that I coded into a binary file that is essentially a save in user results. I'm not a very good coder so excuse the poor code.
The code below shows that I have created a structure called saveresults and by clicking button1, it should get the contents of the binary file and edit them to be the new result. When I run the code the problem seems to be in the line FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary) in the saveres subroutine.
Structure saveresults 'Structure for saving results
Dim numright As Integer
Dim numwrong As Integer
Dim totalnum As Integer
End Structure
'Subroutine aimed at getting stats saved to a text file to eventually be displayed to the user
Sub saveres(saveresults As saveresults, correct As Boolean)
saveresults.totalnum = saveresults.totalnum + 1
'Determining the contents to be saved to the binary file
If correct = True Then
saveresults.numright = saveresults.numright + 1
ElseIf correct = False Then
saveresults.numwrong = saveresults.numwrong + 1
End If
FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary)
FilePut(1, saveresults)
FileClose(1)
End Sub
'attempt at saving results to the binary file
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim correct = True
Dim results As saveresults
FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary)
FileGet(1, results)
saveres(results, correct)
FileClose(1)
End Sub
Any help would be appreciated. Thank you.
Use this instead
FileOpen(1, "1.txt", OpenMode.Binary)
Using the above opens the file in your project's debug folder.
You are referring to text files and binary files as if they are the same thing. They are not. Text files are human readable in Notepad; binary files are not.
I have not used the methods you are attempting since VB 6. Use the .Net System.IO methods. To use these you need to add Imports System.IO at the very top of your code file.
I have broken your code into Subs and Functions that have a single purpose. Reading the file, writing the file, updating the data, and displaying the data. This makes code more maintainable. If your code misbehaves it is easier to find the error and easier to fix if a method has only one thing to do.
The file location in the example is in the same directory as your .exe file. Probably
/bin/Degug.
'A Form level variable to hold the data
Private results As New saveresults
Structure saveresults 'Structure for saving results
Dim numright As Integer
Dim numwrong As Integer
Dim totalnum As Integer
End Structure
'Update the data
Private Sub UpdateResults(Correct As Boolean)
'It is not necessary to include = True when testing a Boolean
If Correct Then
'this is a shortcut method of writin results.numright = results.numright + 1
results.numright += 1
'A Boolean can only be True or False so if it is not True
'it must be False so, we can just use an Else
'No need to check the condition again
Else
results.numwrong += 1
End If
results.totalnum += 1
End Sub
'Write text file
Private Sub SaveResultsFile(results As saveresults, correct As Boolean)
Dim sb As New StringBuilder
sb.AppendLine(results.numright.ToString)
sb.AppendLine(results.numwrong.ToString)
sb.AppendLine(results.totalnum.ToString)
File.WriteAllText("1.txt", sb.ToString)
End Sub
'Read the text file
Private Function ReadResultsFile() As saveresults
Dim ResultsFiLe() = File.ReadAllLines("1.txt")
Dim results As New saveresults With
{
.numright = CInt(ResultsFiLe(0)),
.numwrong = CInt(ResultsFiLe(1)),
.totalnum = CInt(ResultsFiLe(2))
}
Return results
End Function
'Display
Private Sub DisplayResults()
Dim ResultsToDisplay As saveresults = ReadResultsFile()
'The $ indicates an interpolated string, the same thing can be accomplished with String.Format
Label1.Text = $"The correct number is {ResultsToDisplay.numright}. The wrong number is {ResultsToDisplay.numwrong}. The total is {ResultsToDisplay.totalnum}."
End Sub

VB.NET stopping strings being automatically split by spaces

I am building a program in VB that populates a listbox with all the songs in a chosen folder and opens them with media player when you click on them in the list. All of that works but my problem is that pretty much no matter what I do (I've tested this with WMP, VLC, and Winamp) it splits up the argument string by spaces, for example if the file path is C:\Program Files (x86)\Test song.mp3, it will try to open in sequence: C:\Program, then Files, then (x86)\Test, then song.mp3. It works on file paths containing no spaces, but else it always fails.
Private Sub SongListBox_Click(sender As Object, e As EventArgs) Handles SongListBox.Click
Dim song As String = SongListBox.SelectedIndex
If SongListBox.SelectedIndex = "-1" Then
Else
Dim SongPath As String = Pathlist.Items.Item(song)
Dim SongProcess As New ProcessStartInfo
SongProcess.FileName = "C:\Program Files\Winamp\winamp.exe"
SongProcess.Arguments = SongPath
SongProcess.UseShellExecute = True
SongProcess.WindowStyle = ProcessWindowStyle.Normal
MsgBox(Pathlist.Items.Item(song), MsgBoxStyle.Information, "Song")
Dim SongStart As Process = Process.Start(SongProcess)
SongListBox.Select()
End If
End Sub

Writing to a text file in Visual Basic stops at 3074 bytes. Any idea why?

I have developed a small program using Visual Basic Express 2010 that reads a file, scans it line by line, when the line contains some specific text, it manipulates the text and writes that manipulated text to a new file, if that condition is not met, it writes the original line.
It is working ok, gives no errors and completes the run. However, it stops writing to the file at some point. I have checked the files and the only common thing I find between the several tests is that the new files all have 3074 bytes as size. Is this a limitation of VB Express? Am I using the wrong way of writing to the file?
Here a reduced version of the code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Linha As String
Dim datapag As String
'Open File
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim novoficheiro As New System.IO.StreamWriter(OpenFileDialog1.FileName + "2.xml")
Dim Ficheiro As New System.IO.StreamReader(OpenFileDialog1.FileName)
'Scan lines one at a time
Do While Ficheiro.Peek <> -1
Linha = Ficheiro.ReadLine
Dim tratada As Boolean
tratada = False
'Make some changes in specific conditions
If Linha.Contains("<PaymentDueDate>") Then
datapag = Mid(Linha, 17, 8)
Dim composta, Novalinha3 As String
composta = Mid(datapag, 1, 4) + "-"
composta = composta + Mid(datapag, 5, 2) + "-"
composta = composta + Mid(datapag, 7, 2)
Novalinha3 = Replace(Linha, datapag, composta)
novoficheiro.WriteLine(Novalinha3)
tratada = True
End If
'If no changes were made write the original line
If tratada = False Then
novoficheiro.WriteLine(Linha)
End If
Loop
End If
End Sub
End Class
So, the idea is that I have a new version of the file with just some lines changed.
I have added messages throughout the code to show me the contents of the lines sent to the new file and they are all parsed ok, corrected correctly when needed and unchanged when no correction is necessary.
The file just gets truncated at some point, depending on how many different conditions I handle but always resulting in a file with 3074 byte size (the original file is 2787 bytes long, BTW).
Any help?
Thanks in advance!
I believe that you need to flush and close the StreamWriter after your done writing the file and before you exit the function. After the Loop and before the End If, add the line:
novoficheiro.Close()
This should fix the issue.

Inputbox input to streamwriter file

So, in my assignment, we're supposed to create phone directories in the Directories.txt file and then change the listings in the directories. I made a blank directories.txt file and placed that in the debug folder. I also have created a button titled Create a New Phone Directory. When a user clicks on it, the inputbox shows up prompting the user to title the new directory. I am wondering how to get the results from that inputbox that the user typed and use that to create a new directory file in directories.txt and display it in a listbox. I think I have to use stream writer but every time I try, the result in the listbox shows up as system.IO.streamwriter.
This is my current code:
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
inputDirectories = InputBox("Please Enter the Name of the New Directory")
If inputDirectories Is "" Then
MessageBox.Show("Invalid Directory Name")
End If
Dim fileDirectories As IO.StreamWriter = IO.File.CreateText(inputDirectories)
fileDirectories.WriteLine(inputDirectories)
End Sub
The assignment instructions say to use to write line method to add the name of the new file to the directories.txt file but I am totally lost on how to do this.
Any help would be appreciated!
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
'
Dim path As String = "c:\temp\MyTestDirectory.txt"
Dim fileDirectories As System.IO.StreamWriter
Dim inputDirectory As String = ""
'
inputDirectory = InputBox("Please Enter the Name of the New Directory")
If inputDirectory = "" Then
MessageBox.Show("Invalid Directory Name")
Else
If System.IO.File.Exists(path) = False Then
'The file does not exist so create a new file & add the inputted data
fileDirectories = System.IO.File.CreateText(path)
fileDirectories.WriteLine(inputDirectory)
fileDirectories.Flush()
fileDirectories.Close()
Else
'The file exists so append file with the inputted data
fileDirectories = System.IO.File.AppendText(path)
fileDirectories.WriteLine(inputDirectory)
fileDirectories.Flush()
fileDirectories.Close()
End If
End If
'
End Sub
Sub ReadDataBackNow()
' Open the file to read from one line at a time
Dim path As String = "c:\temp\MyTestDirectory.txt"
Dim DataStreamIn As System.IO.StreamReader = System.IO.File.OpenText(path)
Dim TextLines As String = ""
'
Do While DataStreamIn.Peek() >= 0
TextLines = TextLines & DataStreamIn.ReadLine()
Loop
DataStreamIn.Close()
MsgBox(TextLines)
End Sub
UPDATE
Update to answer additional question.
In your button click event add the following line
Listbox1.Items.Add(inputDirectory)
Add the line AFTER the inner IF THEN block so your code would like this
If System.IO.File.Exists(path) = False Then
'The file does not exist so create a new file & add the inputted data
fileDirectories = System.IO.File.CreateText(path)
fileDirectories.WriteLine(inputDirectory)
fileDirectories.Flush()
fileDirectories.Close()
Else
'The file exists so append file with the inputted data
fileDirectories = System.IO.File.AppendText(path)
fileDirectories.WriteLine(inputDirectory)
fileDirectories.Flush()
fileDirectories.Close()
End If
Listbox1.Items.Add(inputDirectory)
Note that you will need several files to answer your question, so you may end up with something like
Directories.txt (contains list of directories)
Friends_Directory.txt
Workmates_Directory.txt
Family_Directory.txt
Friends_Directory.txt (contains list of friends)
Bob 1234567890
Angela 2345678901
Steve 3456789012
Ahmed 4567890123
Fatima 5678901234
Workmates_Directory.txt (contains list of workmates)
CEO_Alan 0987654321
Manager_Daisy 0876543219
Foreman_Judy 0765432198
Colleague_Jill 0654321987
Family_Directory.txt
Bro_Malcolm 1122334455
Sis_Alisha 2233445566
Moms 3344556677
Pops 4455667788
Uncle_Ben 5566778899
Aunty_Sarah 6677889900

VB.NET Read Certain text in a text file

I want my program to read certain text in a text file. For example if I have a text file that contains the following info..
acc=blah
pass=hello
I want my vb.net application to get that the account variable is equal to blah, and the password variable is equal to hello.
Can anyone tell me how to do this?
Thanks
Here is a quick little bit of code that, after you click a button, will:
take an input file (in this case I created one called "test.ini")
read in the values as separate lines
do a search, using regular expressions, to see if it contains any "ACC=" or "PASS=" parameters
then write them to the console
here is the code:
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strFile As String = "Test.INI"
Dim sr As New StreamReader(strFile)
Dim InputString As String
While sr.Peek <> -1
InputString = sr.ReadLine()
checkIfContains(InputString)
InputString = String.Empty
End While
sr.Close()
End Sub
Private Sub checkIfContains(ByVal inputString As String)
Dim outputFile As String = "testOutput.txt"
Dim m As Match
Dim m2 As Match
Dim itemPattern As String = "acc=(\S+)"
Dim itemPattern2 As String = "pass=(\S+)"
m = Regex.Match(inputString, itemPattern, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
m2 = Regex.Match(inputString, itemPattern2, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
Do While m.Success
Console.WriteLine("Found account {0}", _
m.Groups(1), m.Groups(1).Index)
m = m.NextMatch()
Loop
Do While m2.Success
Console.WriteLine("Found password {0}", _
m2.Groups(1), m2.Groups(1).Index)
m2 = m2.NextMatch()
Loop
End Sub
End Class
Have a look at this article
Reading and writing text files with VB.NET
Wile reading the file line by line, you can use String.Split Method with the splitter being "=", to split the string into param name, and param value.
Looks like you've got an INI file of some kind... The best way to read these is using the *PrivateProfile* functions of the windows API, which means you can actually have a proper full INI file quite easily for anything you need. There is a wrapper class here you may like to use.
Microsoft recommends that you use the registry to store this sort of information though, and discourages use of INI files.
If you wish to just use a file manually with the syntax you have, it is a simple case of splitting the string on '=' and put the results into a Dictionary. Remember to handle cases where the data was not found in the file and you need a default/error. In modern times though, XML is becoming a lot more popular for data text files, and there are lots of libraries to deal with loading from these.
My suggestion: you use XML. The .NET framework has a lot of good XML tools, if you're willing to make the transition to put all the text files into XML, it'll make life a lot easier.
Not what you're looking for, probably, but it's a cleaner solution than anything you could do with plain text (outside of developing your own parser or using a lower level API).
You can't really selectively read a certain bit of information in the file exclusively. You'll have to scan each line of the file and do a search for the string "pass=" at the beginning of the line. I don't know VB but look up these topics:
File readers (espically ones that can read one line at a time)
String tokenizers/splitting (as Astander mentioned)
File reading examples
Have you thought about getting the framework to handle it instead?
If you add an entry into the settings tab of the project properties with name acc, type string, scope user (or application, depending on requirements) and value pass, you can use the System.Configuration.ApplicationSettingsBase functionality to deal with it.
Private _settings As My.MySettings
Private _acc as String
Private _pass as String
Public ReadOnly Property Settings() As System.Configuration.ApplicationSettingsBase
Get
If _settings Is Nothing Then
_settings = New My.MySettings
End If
Return _settings
End Get
End Property
Private Sub SetSettings()
Settings.SettingsKey = Me.Name
Dim theSettings As My.MySettings
theSettings = DirectCast(Settings, My.MySettings)
theSettings.acc=_acc
theSettings.pass=_pass
Settings.Save()
End Sub
Private Sub GetSettings()
Settings.SettingsKey = Me.Name
Dim theSettings As My.MySettings
theSettings = DirectCast(Settings, My.MySettings)
_acc=theSettings.acc
_pass=theSettings.pass
End Sub
Call GetSettings in whatever load event you need, and SetSettings in closing events
This will create an entry in the application.exe.config file, either in your local settings \apps\2.0\etc etc directory, or your roaming one, or if it's a clickonce deployment, in the clickonce data directory. This will look like the following:-
<userSettings>
<MyTestApp.My.MySettings>
<setting name="acc" serializeAs="String">
<value>blah</value>
</setting>
<setting name="pass" serializeAs="String">
<value>hello</value>
</setting>
</MyTestApp.My.MySettings>
</userSettings>
Writing your own parser is not that hard. I managed to make one for a game (Using C#, but VB appears to have Regex class too. Using that, the acc variable in your file would be everything up to the = sign, and then blah would be everything past the = to the newline character (\n) Then go to the next line and repeat.
I have written this for you, check it and enjoy with the results, have a great day!
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim acc As New List(Of String)
Dim pass As New List(Of String)
Dim lines() As String = System.IO.File.ReadAllLines(".\credentials.txt")
For Each lineItem As String In lines
Dim vals() As String = lineItem.Split(Convert.ToChar("="))
If vals.Length > 0 Then
Dim lineId As String = vals(0)
If lineId = "acc" Then
acc.Add(vals(1))
ElseIf lineId = "pass" Then
pass.Add(vals(1))
End If
End If
Next
TextBox_acc.Text = String.Join(Environment.NewLine, acc)
TextBox_pass.Text = String.Join(Environment.NewLine, pass)
End Sub
End Class