Assistance with Copy & Paste VB System - vb.net

The system is meant to work so that whenever the gta_sa process stops running, it copies the file selected when browsing cmdFile to cmdStorage's location. Problem I have right now is that it doesn't store the new file in .txt, but rather just as .file. It's openable, but not as default.
Also, I wasn't sure how to do the detection on when gtasa process was recently closed so I had to use if the process is active. I'd really appreciate it for some help, thanks.**
EDIT: Maybe it needs to use a timer? Not sure, thanks again.
Imports System.Diagnostics
Imports System Imports System.ComponentModel
Public Class frmChatLog
Dim ofdDone
Dim fldDone
Dim Completed
Private Sub cmdStorage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdStorage.Click
Using fld As New FolderBrowserDialog()
If fld.ShowDialog() = Windows.Forms.DialogResult.OK Then
MessageBox.Show("Selected " & fld.SelectedPath)
fldDone = fld.SelectedPath
cmdStorage.Enabled = False
End If
End Using
End Sub
Private Sub cmdFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdFile.Click
Using ofd As New OpenFileDialog()
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
MessageBox.Show("Selected " & ofd.FileName)
ofdDone = ofd.FileName
cmdFile.Enabled = False
End If
End Using
End Sub
Private Sub cmdStart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdStart.Click
If cmdFile.Enabled = False And cmdStorage.Enabled = False Then
Do Until Process.GetProcessesByName("gta_sa").Count > 0
If Process.GetProcessesByName("gta_sa").Count > 0 Then
MsgBox("Game is on")
Else
System.IO.File.Move(ofdDone, fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss"))
Completed = fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss")
Completed.ChangeExtension(".txt")
Exit Do
End If
Loop
End If
End Sub
End Class

Problem I have right now is that it doesn't store the new file in .txt, but rather just as .file.
To fix that, change this line near the bottom of your code:
System.IO.File.Move(ofdDone, fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss"))
to this:
File.Move(ofdDone, Path.Combine(fldDone, Now.ToString("ddMMyyHHmmss") & ".txt"))
Then get rid of any line that mentions your Completed variable. You may also need to add an Imports System.IO to the top of the file.

Related

File.create shows no errors but doesnt create file?

I'm trying to copy a file from an external drive by reading its contents, creating a new file elsewhere and writing the contents into it. My code shows no errors (using MSV) but when I try to 'download' the file, it completes the code but no file is created.
Can anyone help?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim FileReader As String
FileReader = My.Computer.FileSystem.ReadAllText(Label32.Text)
Dim fbd As FolderBrowserDialog = New FolderBrowserDialog
Dim DownloadLocation As String
If fbd.ShowDialog() <> DialogResult.Cancel Then
DownloadLocation = fbd.SelectedPath
File.Create(fbd.SelectedPath & "pandora speedsign log.txt").Dispose()
File.WriteAllText(fbd.SelectedPath & "pandora speedsign log.txt", FileReader)
MessageBox.Show("success!!")
End If
'File.Create("C:\Users\%UserProfile%\Downloads" & DownloadFileDate & ".txt")
'File.WriteAllText("C:\Users\%USERPROFILE%\Downloads" & DownloadFileDate & ".txt", FileReader)
End Sub
I've been looking for different ways of creating the file, different ways of writing the file but nothing seems to work.
We can significantly simplify the code like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fbd As New FolderBrowserDialog()
If fbd.ShowDialog() <> DialogResult.Ok Then Exit Sub
Dim outputPath As String = IO.Path.Combine(fbd.SelectedPath, "pandora speedsign log.txt")
IO.File.Copy(Label32.Text, outputPath)
End Sub

How to create a progress bar that updates simultaneously with a file transfer

As the title implies, I am trying to create a progress bar that updates with a file transfer. I am currently using Visual Studio 2019. I have been through dozens of articles and videos all claiming to do just this. After many days of testing, I have gotten close, but the progress bar will still only update after the file transfer is complete. I am using multi threading techniques to accomplish just this much. I would very much appreciate if someone could just lay it down for me on how to do this. Here is my code so far. It doesn't really help for making it but you can at least see what I am trying to achieve. I also left out some large chunks of commented out test script.
Summary of what I need to is: Create a script that will copy the specified directory and all sub directories. While doing this I would like the progress bar to move with the file transfer.
Imports System.ComponentModel
Imports System.Threading
Imports System
Imports System.IO
Public Class Form1
Private Sub BtnStartTransfer_Click(sender As Object, e As EventArgs) Handles btnStartTransfer.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Delegate Sub DelegateProgressBarMax(ByVal check As Integer)
Private Sub ProgressBarUpdate(ByVal check As Integer)
If pBar1.InvokeRequired = True Then
Invoke(Sub() pBar1.Value = check)
Else
pBar1.Value = check
End If
End Sub
Private Delegate Sub DelegateUpdateOutput(ByVal check2 As String)
Private Sub OutputUpdate(ByVal check2 As String)
If txtOutput.InvokeRequired = True Then
Invoke(Sub() txtOutput.Text = txtOutput.Text & check2 & Environment.NewLine)
Else
txtOutput.Text = txtOutput.Text & check2
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim getCopyFrom As String = txtCopyFrom.Text
Dim getCopyTo As String = txtCopyTo.Text
Dim splitUser() As String = getCopyFrom.Split("\")
Dim finalValue As String = splitUser.Length - 1
Dim stringValue As String = CStr(splitUser(finalValue))
Dim getUser As String
'If MsgBox("Is this the correct user?: " & stringValue, vbYesNo + vbQuestion) = vbYes Then
' getUser = stringValue
'Else
' getUser = InputBox("Enter in the correct Username")
'End If
Dim checkCopyFrom As New IO.DirectoryInfo(getCopyFrom)
Dim checkCopyTo As New IO.DirectoryInfo(getCopyTo)
If checkCopyFrom.Exists Then
Else
MsgBox("The location you are trying to copy from does not exist.")
Exit Sub
End If
If checkCopyTo.Exists Then
Else
MsgBox("The location you are trying to copy to does not exist.")
Exit Sub
End If
'Copying the Desktop folder
Dim dirDesktop = getCopyFrom & "\Desktop"
Dim getDir = IO.Directory.GetFiles(dirDesktop, "*", IO.SearchOption.AllDirectories)
Dim fileTotal As Integer = getDir.Length
Dim filesTransferred As Integer = 0
Dim di As New DirectoryInfo(dirDesktop)
Dim fiArr As FileInfo() = di.GetFiles("*", SearchOption.AllDirectories)
Dim diArr As DirectoryInfo() = di.GetDirectories("*", IO.SearchOption.AllDirectories)
Dim fri As FileInfo
Dim fol As DirectoryInfo
For Each fri In fiArr
filesTransferred += 1
BackgroundWorker1.ReportProgress(CInt(filesTransferred * 100 \ fiArr.Length), True)
OutputUpdate(fri.Name)
'File.Copy(dirDesktop & "\" & fri.Name, getCopyTo & "\" & fri.Name, True)
'My.Computer.FileSystem.CopyDirectory(getCopyFrom & "\Desktop", getCopyTo & "\Users\" & getUser & "\Desktop", False)
Next fri
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
pBar1.Value = e.ProgressPercentage
End Sub

vb.net get contextmenustrip applicable to multiple pictureboxes

In my form I have several pictureboxes and one contextmenustrip, the contextmenustrip is supposed to use at all these pictureboxes.
A tool in the contextmenustrip is to open and view the a pdf file.
The current code is:
Private Sub ViewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewToolStripMenuItem.Click
Process.Start("C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe", "C:\vb_test\" + picDrawing(1))
End Sub
I have no idea how the tool can determine which picturebox is focused and open different files.
I am using vb.net.
It seems that ContextMenu.SourceControl returns always Nothing in particular situations. I verified this problem on VS2010 when I put my ToolStripMenuItem inside a ToolStripDropDownMenu. So the answer posted by #Justin Ryan couldn't working.
A workaround could be manually set a variable when opening ContextMenu with its SourceControl.
Public Class Form1
Dim ctrlSourceControl As Control
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
AddHandler Me.ContextMenuStrip1.Opening, AddressOf setSourceControl
End Sub
Private Sub setSourceControl(sender As Object, e As System.ComponentModel.CancelEventArgs)
Me.ctrlSourceControl = CType(sender, ContextMenuStrip).SourceControl
End Sub
Private Sub Item1ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles Item1ToolStripMenuItem.Click
MsgBox(Me.ctrlSourceControl.Name)
End Sub
End Class
From this question, Tim Lentine shows how to use the SourceControl property Of a ContextMenuStrip to determine the control which opened the context menu:
Private Sub mnuWebCopy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuWebCopy.Click
Dim myItem As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim cms As ContextMenuStrip = CType(myItem.Owner, ContextMenuStrip)
MessageBox.Show(cms.SourceControl.Name)
End Sub
This answer is likely the same as tezzo's. Just used to this
scenario a lot, and wanted to share some security checks among many
others that may help.
Assuming
ONLY PictureBoxes can show your ContextMenu named MyContextMenu :
and you have a ToolStripMenuItem named ViewToolStripMenuItem
Declarations :
Option Strict On
Option Explicit On
Option Infer Off
Imports System.IO
' File.Exist()
Imports System.Diagnostics
' Process.Start()
Public Class Form1
Private p_SelectedPictureB As PictureBox
Private p_AcroRedPath As String = "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe"
Private p_ImageFolderPath As String = "C:\vb_test\"
Private p_TargetFileName As String = ""
' ...
End Class
Handle the Opening Event of your MyContextMenu [ContextMenu]
either by a Handles MyContextMenu.Opening hook
or AddHandler MyContextMenu.Opening, AddressOf MyContextMenu_Opening
Private Sub MyContextMenu_Opening( _
sender As Object, e As System.ComponentModel.CancelEventArgs) _
Handles MyContextMenu.Opening ' Requires Private WithEvents MyContextMenu
'Try
p_SelectedPictureB = DirectCast(MyContextMenu.SourceControl, PictureBox)
If p_SelectedPictureB.Image IsNot Nothing Then
ViewToolStripMenuItem.Enabled = True
Select Case True
Case p_SelectedPictureB Is PictureBox1:
p_TargetFileName = picDrawing(1)
ViewToolStripMenuItem.Text = "Open [" + p_TargetFileName + "]"
Case p_SelectedPictureB Is PictureBox2:
p_TargetFileName = picDrawing(2)
ViewToolStripMenuItem.Text = "Open [" + p_TargetFileName + "]"
' ...
Case Else
ViewToolStripMenuItem.Enabled = False
ViewToolStripMenuItem.Text = "Open [<Wrong PBox>]"
p_TargetFileName = ""
'e.Cancel = True
End Select
Else
ViewToolStripMenuItem.Enabled = False
ViewToolStripMenuItem.Text = "Open [<No Image>]"
p_TargetFileName = ""
'e.Cancel = True
End If
'Catch CurrentException As Exception
' MessageBox.Show(CurrentException.Message)
' ViewToolStripMenuItem.Enabled = False
' p_TargetFileName = ""
' e.Cancel = True
'End Try
' ^^ remove commenting if you're unsure.
End Sub
Prefer the use of top declared variables.
If you write plain file/folder paths inside a method or function, you could loose track of it quickly, and some time later, you don't understand why your application suddenly started to crash (because the file went deleted/application uninstalled, or the folder renamed)
=> Put path to File/Folder in a global variable
However, the best move is to retrieve that path at Runtime, and ensure the existence of the File/Folder before going further...
Private Sub ViewToolStripMenuItem_Click( _
sender As Object, e As EventArgs) _
Handles ViewToolStripMenuItem.Click
Dim TargetFile As String = p_ImageFolderPath + p_TargetFileName
If File.Exists(TargetFile) Then
' (p_AcroRedPath existence checked when application starts)
Process.Start(p_AcroRedPath, TargetFile)
Else
MessageBox.Show("The File [" + TargetFile + "] doesn't exist.")
End If
End Sub

VB.NET Warning , CPU Application

The warning is : An error occurred creating the form. See Exception.InnerException for details. The error is: Cannot load Counter Name data because an invalid index '' was read from the registry.
My Code is :
Imports System
Imports System.Management
Imports System.Diagnostics
Public Class Form1
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Dim cpuLoad As Integer = CDec(PerformanceCounter1.NextValue.ToString())
cpuLoad = 100 - cpuLoad
Label1.Text = cpuLoad.ToString() & "%"
On Error Resume Next
ProgressBar1.Value = cpuLoad.ToString
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Timer1.Start()
Label2.Text = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\SYSTEM\CentralProcessor\0", "ProcessorNameString", Nothing)
label3.text = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\SYSTEM\CentralProcessor\0", "~MHz", Nothing) & " Mhz"
End Sub
End Class
Have a look at this question. I found this, and many more examples suggesting that your problem results from one or more corrupted registry entries. Pablissimo's answer provides an explanation of the problem, and the relevant steps to rebuild these entries.
Click Start, type cmd right click cmd.exe, and select Run as
administrator. At the prompt, type lodctr /r and press ENTER.
First of all your cpu counter gives a strange value on my pc."2 times higher than it is"
what i use is also a performance counter but the value is almost the same as in windows task manager.
Dim CpuCounter As New PerformanceCounter()
Dim CpuResult As New Integer
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
With CpuCounter
.CategoryName = "Processor"
.CounterName = "% Processor Time"
.InstanceName = "_Total"
End With
CpuResult = CpuCounter.NextValue
CpuLabel.Text = CpuResult & "%"
CpuBar.Value = CpuResult
End Sub
the other thing is ...
Your code to get the ProcessorNameString and the Mhz is working on my computer..
But you can also use it like this.
you need to Imports Microsoft.Win32 "but of course you already have that"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cpuName As String
Dim cpuFreq As String
Dim regKey As RegistryKey
regKey = Registry.LocalMachine
regKey = regKey.OpenSubKey("HARDWARE\DESCRIPTION\System\CentralProcessor\0", False)
cpuName = regKey.GetValue("ProcessorNameString")
cpuFreq = regKey.GetValue("~MHz")
Label2.Text = cpuName
Label3.Text = cpuFreq & " MHz"
End Sub
And if this does not work you can also use WMI "ManagementObjectSearcher" for it.
you need to Imports System.Management
and Add reference System.Management to your project.
then you can use this code in the form load event to get the same info
Dim cpuName As String
Dim cpuFreq As String
Try
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_Processor")
For Each queryObj As ManagementObject In searcher.Get()
cpuName = queryObj("Name")
cpuFreq = queryObj("CurrentClockSpeed")
Label2.Text = cpuName
Label3.Text = cpuFreq & "MHz"
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub