Visual Basic 2013 Text duplicating - vb.net

I had issues with a program, so
I was making a notepad program for my XP overlay thingy, and whenever I reopen it twice, the text is duplicated.
For example when I type in
test
and i reopen it second, it outputs:
testtest
I have no idea what is causing this, but it certainly is annoying.
If I could get some help with this issue that would be awesome!
Heres my code:
Private Sub notepad_X_Click(sender As Object, e As EventArgs) Handles notepad_X.Click
Try
My.Computer.FileSystem.WriteAllText("C:\XP\notepad.txt", RichTextBox1.Text, True)
RichTextBox1.Text = ""
Catch Exc As System.IO.DirectoryNotFoundException
My.Computer.FileSystem.CreateDirectory("C:\XP")
End Try
notepad.Enabled = False
notepad.Visible = False
End Sub
Private Sub Notepad_btn_Click(sender As Object, e As EventArgs) Handles StartM_Notepad.Click
RichTextBox1.Text = ""
Try
RichTextBox1.Text = My.Computer.FileSystem.ReadAllText("C:\XP\notepad.txt")
Catch Exc As System.IO.DirectoryNotFoundException
My.Computer.FileSystem.CreateDirectory("C:\XP")
End Try
notepad.Enabled = True
notepad.Visible = True
End Sub

This happens because you have explicitly specified it to do so. You are using the FileSystem.WriteAllText() overload with 3 parameters, where you've set the third parameter to True. That parameter (called append) specifies if you want to append text to your file or overwrite it.
As you've told it to append text to your file it will just write the new text you give it (whatever's in RichTextBox1) after the already existing text. Set the parameter to False so that the text gets overwritten instead:
My.Computer.FileSystem.WriteAllText("C:\XP\notepad.txt", RichTextBox1.Text, False)

Related

Saving a setting to MySettings and exiting the program isn't working

I'm having a problem with saving a setting to My Project and then exiting my program with an 'End' statement. If I save the setting but don't execute the end statement, everything works. If I save the setting and then execute the 'End', the setting doesn't get saved. Here's some code that illustrates the problem:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'reads the last setting correctly
TextBox1.Text = My.Settings.MySetting
End Sub
Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
'write value, don't exit; works
My.Settings.MySetting = TextBox1.Text
End Sub
Private Sub btnWriteEnd_Click(sender As Object, e As EventArgs) Handles btnWriteEnd.Click
'write value and end; fails
My.Settings.MySetting = TextBox1.Text
End
End Sub
End Class
When I execute the code, whatever was last in My.Settings.MySetting appears in TextBox1. If I change the text in the textbox and click on the 'Write' button and manually exit the program by clicking on the 'X', the new text appears properly changed when I execute the program again. If I change the text and exit programmatically by clicking on 'WriteEnd', the changed setting text doesn't get written to 'MySetting'.
What am I doing wrong?
Thanks
Settings will be saved automatically at shutdown by default, so there's generally no need to call Save. End is definitely the issue. NEVER use End. Call Close on the startup form or call Application.Exit. I compare End with a bouncer grabbing someone by the scruff of the neck and throwing them out, spilling their drink on everyone and leaving their jacket behind, rather than asking them to leave of their own accord.

Folder Browser Replacement

I want to be able to add multiple download links and for them to go into a single folder which is selected by the user in a Folder Browser Dialog
The code you see below works great except only for a single file. I have tried changing all 'savefiledialog1' to 'folderbrowserdialog1' instead. However this leads to me clicking download and nothing happening even if only a single link is entered.
Private Sub BtnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
If (SaveFileDialog1.ShowDialog() = DialogResult.OK) Then
txtSave1.Text = SaveFileDialog1.FileName
btnDownload.Enabled = True
End If
End Sub
' ------------ DOWNLOADING SECTION ------------
Private WithEvents HTTPCLIENT As WebClient
Private Sub BtnDownload_Click(sender As Object, e As EventArgs) Handles
btnDownload.Click
btnDownload.Enabled = False
txtSave1.Enabled = False
btnBrowse.Enabled = False
btnDownload.Enabled = False
HTTPCLIENT = New WebClient
Dim Download As String
Download = Links(i)
Dim User = Environment.UserName
Dim Save As String = txtSave1.Text
Try
HTTPCLIENT.DownloadFileAsync(New Uri(Download), Save)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I expected the folder browser dialog to just be a general save path where the file being downloaded is placed into that folder, however I am given an error.
The code above works but only for a single file.
I have code that can retrieve the download name and extension which I plan to add to the path once i figure this part out.
You can use the FolderBrowserDialog. Once you get the path, you combine it with each filename you will download. Use System.IO.Path.Combine()
Private Sub BtnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Using fbd As New FolderBrowserDialog()
If fbd.ShowDialog() = DialogResult.OK Then
txtSave1.Text = fbd.SelectedPath
btnDownload.Enabled = True
End If
End Using
End Sub
Private Sub BtnDownload_Click(sender As Object, e As EventArgs) Handles btnDownload.Click
Try
btnDownload.Enabled = False
txtSave1.Enabled = False
btnBrowse.Enabled = False
btnDownload.Enabled = False
Dim exceptionMessages As New List(Of String)
Using client = New WebClient()
' configure client here as needed i.e. add Credentials
For Each link In Links
Try
client.DownloadFileAsync(New Uri(link), Path.Combine(txtSave1.Text, link))
Catch ex As Exception
exceptionMessages.Add(ex.Message)
End Try
Next
End Using
If exceptionMessages.Any() Then MessageBox.Show($"Exception{If(exceptionMessages.Count > 1, "s", "")}: {String.Join(Environment.NewLine, exceptionMessages)}")
Finally
txtSave1.Enabled = True
btnBrowse.Enabled = True
btnDownload.Enabled = True
End Try
End Sub
Note that I will not post an answer with IDisposable objects without Using (in most cases) so FolderBrowserDialog and WebClient are both in Usings. You may need to add additional configuration to the WebClient before downloading.
Also, you probably don't want a separate message for each Exception, if any. So the messages can be cached and shown all at once.
I inserted a Finally for you to set control states back to default when done. This is up to you.
Lastly, the work is being done on a UI thread as evidenced by it being one inside the button click handler. You should move it off the UI even though you aren't blocking. This is outside the scope of the question.

Can't get checking if file exists using textboxes to work

I've been racking my brain for days over this code and I just can't seem to get it working. I've researched and researched with no luck. I have four textboxes on my form. Two textboxes is a folder location and the other two textboxes are file locations. I'm trying to use a function that will return true or false telling if the files in the two textboxes exist or not. I don't see anything at all wrong with this code and it just won't work! I'm sure it's something simple I'm overlooking. Maybe someone else can spot it!
Private Function doesFileExist(folderPath, fileName) As Boolean
If IO.File.Exists(folderPath & "\" & fileName) Then
Return True
Else
Return False
End If
End Function
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If doesFileExist(txtCPU.Text, txtFileCPU.Text) And
doesFileExist(txtGPU.Text, txtFileGPU.Text) Then
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
Else
chkStart.Checked = False
chkStart.Text = "Start Monitor"
End If
Else
chkStart.Checked = False
MessageBox.Show("Please check directory & file locations!", "Error!", MessageBoxButtons.OK)
End if
End Sub
I want to mention that before I tried nested if statements on this I also tried to separate them both like so..
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If Not doesFileExist(txtCPU.Text, txtFileCPU.Text) And
Not doesFileExist(txtGPU.Text, txtFileGPU.Text) Then
chkStart.Checked = False
MessageBox.Show("Please check directory & file locations!", "Error!", MessageBoxButtons.OK)
Exit Sub
End If
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
Else
chkStart.Checked = False
chkStart.Text = "Start Monitor"
End If
End Sub
Both of these ways will show the messagebox if the application is ran with the checkbox checked on start up. Not only will it show the messagebox it also shows the messagebox twice! I've yet to figure that one out!
Your check file exists can be simplified... (It's been a while since I used VB so apologies for any syntax errors, I don't have an IDE to hand)
Function DoesFileExist(Folder as String, Filename As String) As Boolean
Return IO.File.Exists(IO.Path.Combine(Folder, Filename))
End Function
Re: Changing whether the "check" checkbox is set shouldn't perform the check itself - otherwise you only check when people click. (Incidentally, I'm guessing you're getting a message twice as code elsewhere ticks/unticks this checkbox, but it's only a guess).
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
PollTimer.Start()
Else
chkStart.Text = "Start Monitor"
PollTimer.Stop()
End if
End Sub
Finally... You need to define when your check will happen. Ideally, you'd want to use a FileSystemWatcher which will give you events when the file system changes, but you can also poll using a timer...
Private PollTimer As System.Timers.Timer
Then in your Form Main, do some initial timer setup...
...
PollTimer = New System.Timers.Timer()
PollTimer.Interval = 30000 ' Seconds
AddHandler PollTimer.Elapsed, AddressOf CheckExistsNow
PollTimer.Start()
...
And finally the code to run every time we want to make the check....
Sub CheckExistsNow(sender As Object, e As System.Timers.ElapsedEventArgs)
If Not DoesFileExist(txtGPU.Text, txtFileGPU.Text) Then
' Handle the missing file.
End if
End Sub

Creating my own CMD in vb.net

I'm in need of help with this program which I'm trying to create.
I'm pretty new to programming in general, so please bear with me.
So what I'm trying to create right now, is my own command prompt, and with that said, let me tell you what I want in the command prompt.
As we know from the normal CMD on windows OS systems, we have our input box(or whatever) which we can use to type commands, such as "start google.com", or "ipconfig" etc...
and we have our output, which tells us the results from the commands we typed.
And I wanna create the exact same thing, just with my own UI and some extras which I'm gonna add later.
Here is my issue tho, whenever I type the shell command in my textbox and execute it, it prints out the exception message, so basically it doesn't run the command.
Here is the code:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Dim tmp As System.Windows.Forms.KeyPressEventArgs = e
If tmp.KeyChar = ChrW(Keys.Enter) Then
Try
Shell(TextBox1.Text)
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = TextBox1.Text
Catch ex As Exception
RichTextBox1.Clear()
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = ex.Message
End Try
TextBox1.Text = ""
Else
End If
End Sub
I'd really like some examples if possible, since I'm new and I probably wouldn't understand much without examples.
Using a process object instead of a shell is a lot better of an option for having a conversation with cmd. Here's an example of a simple function that you can pass commands to that will return the command's response. This example just does one command/response, but you can use the same process shown below to enter into a dialog with cmd.exe:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox(ExecuteCommand("ipconfig /all"))
End Sub
Private Function ExecuteCommand(ByVal command As String) As String
Dim response As String = Nothing
Dim p As New System.Diagnostics.Process
Dim psi As New System.Diagnostics.ProcessStartInfo("cmd.exe")
With psi
.UseShellExecute = False
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.CreateNoWindow = True
End With
p = Process.Start(psi)
With p
.StandardInput.WriteLine(command)
.StandardInput.Close()
If .StandardError.Peek > 0 Then
response = .StandardError.ReadToEnd
.StandardError.Close()
Else
response = .StandardOutput.ReadToEnd
.StandardOutput.Close()
End If
.Close()
End With
Return response
End Function
And as you'll see if you run the code above, you can certainly use commands like ipconfig

How to check if a folder exists automatically without ".click" function

I have a problem. I have a program written in Visual Basic using Visual Studio 2013 and it works good. The problem is that I want the program to check if a folder exists on program start-up and return a text value in a label without having to manually "click" the label. I have searched and cannot find anything, maybe I'm not searching for the right thing?
Here is a sample of the check:
''//ASDG_JR check
Private Sub lbl_asdg_jr_pres_Click(sender As Object, e As EventArgs) Handles lbl_asdg_jr_pres.Click
If My.Computer.FileSystem.DirectoryExists(user_txt_dir.Text & "\#ASDG_JR_v0.14") Then
lbl_asdg_jr_pres.Text = "All good!"
btn_asdg_di.Text = ".zip file downloaded already"
btn_asdg_unzip.Text = "unzipped and installed already"
btn_asdg_di.Enabled = False
btn_asdg_unzip.Enabled = False
Else
lbl_asdg_jr_pres.Text = "Use buttons ----->"
btn_asdg_di.Enabled = True
btn_asdg_unzip.Enabled = True
End If
End Sub
Place your code inside the form's load event.
Private Sub myForm_Load(sender As System.Object, e As System.EventArgs) Handles myForm.Load
'If directoryExists Then update label
End Sub