Get data from Text file Print to Label - vb.net

Just to keep this short I am working on a simple game to be played with anyone in the world who be interested in it, and because I am creating said game I decided to work on a simple launcher for the game one that pings the website for a version, checks that version with a stored text file with the game already installed and see if its a difference in version. If its a difference in version the launcher downloads the game. If the person does not already have the game installed it downloads the game for them.
Now for my problem why I am posting here, I am trying to get the text file already stored on the computer from the AppData directory to be read by the launcher and use it as an comparison with the version on the website. This is what I have for the on launch:
On Launch:
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim wc As New Net.WebClient
Text = wc.DownloadString("https://dl.dropboxusercontent.com/u/47132467/version.txt")
If My.Computer.FileSystem.FileExists("C:\Program Files\SC\SC.exe") Then
StartBtn.Enabled = True
StartBtn.Visible = True
Else
StartBtn.Enabled = False
StartBtn.Visible = False
End If
If My.Computer.FileSystem.FileExists("C:\Program Files\SC\Readme.txt") Then
ReadMeBtn.Visible = True
Else
ReadMeBtn.Visible = False
End If
End Sub
In short I am trying to figure out how to make a text file from the computer itself stored in AppData under Environ("AppData") & "\SC\version.txt" Been trying to figure out how to get the program to Read the local stored text file and put it as a variable where the program will compare it with the text file online. Thanks in Advanced! Sorry if I confuse anyone my brain is in derp mode trying to figure this out for a while now.

Here are 2 Functions Read & Write:
Public Function GetFileContents(ByVal FullPath As String, _
Optional ByRef ErrInfo As String = "") As String
Dim strContents As String
Dim objReader As StreamReader
Try
objReader = New StreamReader(FullPath)
strContents = objReader.ReadToEnd()
objReader.Close()
Return strContents
Catch Ex As Exception
ErrInfo = Ex.Message
End Try
End Function
Public Function SaveTextToFile(ByVal strData As String, _
ByVal FullPath As String, _
Optional ByVal ErrInfo As String = "") As Boolean
Dim Contents As String
Dim bAns As Boolean = False
Dim objReader As StreamWriter
Try
objReader = New StreamWriter(FullPath)
objReader.Write(strData)
objReader.Close()
bAns = True
Catch Ex As Exception
ErrInfo = Ex.Message
End Try
Return bAns
End Function
Call:
Dim File_Path as string = Environ("AppData") & "\SC\version.txt"
Dim versionStr as String = GetFileContents("File_Path")
Label1.text = versionStr
Label1.text.refresh ''// Sometimes this may be required depending on what you are doing!

if you want to read the version directly, rather than a text file, have a look at this code:
If My.Computer.FileSystem.FileExists(fn) Then
Dim fv As FileVersionInfo = FileVersionInfo.GetVersionInfo(fn)
If fv Is Nothing Then Return -1 'file has no version info
Return fv.FileMajorPart * 100000 + fv.FileMinorPart * 1000 + fv.FileBuildPart
Else
Return 0 'file does not exist
End If

Related

Checks The Informations In Text File. VB.NET

I work on a project "SignInLogeIn" using Visual Basic.NET.
I save the user informations in text file.
the name of the file is "data.txt".
to create a new account in my program. you must enter the name,email,password and the program write the informations in textfile.
i use "Streamwritter" to write the informations.
when user create a new account The program checks if the email entered by the user is already in the text file that contains the users' information.
and the program checks from informations by "StreamReader". it reads the information in text file and checks.
I have the problem.
when I CREATE A new account. problem appears.
and the problem is
"
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'D:\1- Anas Files\Projects\VisualBasic.NET\SignInLogIn\SignInLogIn\SignInLogIn\bin\Debug\Data.txt' because it is being used by another process.
"
I think the problem is that I used the file twice
Once to write and once to read.
The error occurs in this line "Dim sw As New StreamWriter("Data.txt")".
how can i solve this problem ?
this is the code of "SignIn" button
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
Dim strEmail As String = txtEmail.Text
Dim Reg As New Regex("^\w+([-_.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")
If txtUserName.Text.Trim() = "" Or txtEmail.Text.Trim() = "" Or txtPassword.Text.Trim() = "" Then
MsgBox("Please Enter All Input")
If Not Reg.IsMatch(strEmail) Then
MsgBox("Please Enter Email")
End If
Else
Dim sr As New StreamReader("Data.txt")
Dim sw As New StreamWriter("Data.txt")
Dim strPerson As String = txtUserName.Text & ";" & txtEmail.Text & ";" & txtPassword.Text
Dim line As String = ""
Do
line = sr.ReadLine()
Dim arrData As String() = line.Split(";")
If arrData(1) = strEmail Then
MsgBox("Please Change Email")
Else
sw.WriteLine(strPerson)
sw.Close()
End If
Loop While line <> Nothing
sr.Close()
End If
End Sub
You open twice the same file. First, to read and second to write, this is why you cannot write.
Dim sr As New StreamReader("Data.txt")
Dim lines As String = sr.ReadToEnd().Split(Environment.NewLine)
sr.Close()
Dim strPerson As String = txtUserName.Text & ";" & txtEmail.Text & ";" & txtPassword.Text
Dim sw As New StreamWriter("Data.txt")
For Each line As String In lines
Dim arrData As String() = line.Split(";")
If arrData(1) = strEmail Then
MsgBox("Please Change Email")
Exit For
Else
sw.WriteLine(strPerson)
Exit For
End If
Next
sw.Close()
Streams need to be closed and disposed. They are usually put in Using blocks.
I wasn't quite sure of the program flow you wanted. It seemed, since you created a writer and a reader you intended to add to user to the file if they were not listed.
I broke out some of the code into separate methods. I used System.IO since we have a simple text file.
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
If ValidInput() Then
Dim strPerson As String = $"{txtUserName.Text};{txtEmail.Text};{txtPassword.Text}"
If Not IsUserInFile(strPerson) Then
File.AppendAllText("Data.txt", strPerson & Environment.NewLine)
End If
End If
End Sub
Private Function ValidInput() As Boolean
Dim strEmail As String = txtEmail.Text
Dim Reg As New Regex("^\w+([-_.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")
If txtUserName.Text.Trim() = "" OrElse txtEmail.Text.Trim() = "" OrElse txtPassword.Text.Trim() = "" Then
MsgBox("Please Enter All Input")
Return False
If Not Reg.IsMatch(strEmail) Then
MsgBox("Please Enter Email")
Return False
End If
End If
Return True
End Function
Private Function IsUserInFile(Person As String) As Boolean
Dim p = Person.Split(";"c)
Dim lines = File.ReadAllLines("Data.txt")
For Each line In lines
If Person = line Then
Return True
End If
Dim fields = line.Split(";"c)
If fields(0) = p(0) AndAlso fields(2) = p(2) AndAlso fields(1) <> p(1) Then
MessageBox.Show("Please Change Email")
Return False
End If
Next
Return False
End Function
This is going to get messy and slow if there are too many users. This info should really be in a database. The worst thing is the passwords should always be salted and hashed; never stored as plain text even is a database.

Vb.net problems download

How can I do a check that first download something and only after that it starts up the program.exe?
I already tried to do something like this but it excutes the file when the download is not finished and it throws some errors.
my Code:
Dim client As WebClient = New WebClient
Dim SourcePath As String = "C:\ProgramData\KDetector\UserAssistView.exe"
Dim SaveDirectory As String = "C:\ProgramData\KDetector"
Dim FileName As String = System.IO.Path.GetFileName(SourcePath)
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, FileName)
If System.IO.File.Exists(SavePath) Then
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
Else
client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"), "C:\ProgramData\KDetector\")
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
End If
You are calling the asynchronous DownloadFile method. Asynchronous method will not block the calling thread.
In order to avoid the problem, your code must be like this:
Dim downloadLink As String = "http://www.nirsoft.net/utils/userassistview.zip"
Dim saveFilePath As String = "C:\ProgramData\KDetector\userassistvkew.zip"
Dim fileName As String = Path.GetFileNameWithoutExtension(saveFilePath)
Dim client As WebClient = New WebClient
Try
CheckExsist(saveFilePath, fileName)
'Before was client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"))
client.DownloadFile(downloadLink, saveFilePath)
MsgBox("Download file completed. File saved in: " & saveFilePath)
'Zip extraction stuff
Catch ex As Exception
MsgBox(ex.Message)
End Try
This is the CheckExsist sub:
Private Sub CheckExsist(ByRef sourcePath As String, ByVal fileName As String, Optional ByVal counter As Integer = 1)
If System.IO.File.Exists(sourcePath) Then
sourcePath = sourcePath.Replace(Path.GetFileName(sourcePath), "") & fileName & "(" & counter & ")" & Path.GetExtension(sourcePath)
counter += 1
CheckExsist(sourcePath, fileName, counter)
End If
End Sub
I manage to download the software (from the official website) and save it as a .zip. Code the last few rows to programmatically extract the .zip, if you ecounter any problem or bug feel free to ask with another question. Anyways there are alot of post on SO regarding zip extraction on vb.net

Process.Start() with "manage-bde.exe" crashing in VB.NET

I'm trying to start manage-bde.exe as a new process in VB.net but when it tries to start the proc, Bitlocker crashes. Could anyone please tell me what I'm doing wrong here? This code was converted from C# where it works all day long....
Code:
Private Sub btnLock_Click(sender As Object, e As EventArgs) Handles btnLock.Click
Dim drvSelected As String = cmbDriveSelect.SelectedValue.ToString()
Dim sysDirWithBDE As String = Environment.SystemDirectory + "\manage-bde.exe"
Dim lockStatus As String = String.Empty
' This is the code for the base process
Dim myProcess As New Process()
' Start a new instance of this program
Dim myProcessStartInfo As New ProcessStartInfo(sysDirWithBDE, " -lock " + drvSelected.Remove(2))
'Set Use Shell to false so as to redirect process run info to application
myProcessStartInfo.UseShellExecute = False
myProcessStartInfo.RedirectStandardOutput = True
myProcess.StartInfo = myProcessStartInfo
Try
myProcess.Start()
lblDriveLockMsg.Show()
Catch err As Exception
lblDriveLockMsg.Text = err.Message
End Try
'Read the standard output of the process.
lockStatus = myProcess.StandardOutput.ReadToEnd()
If lockStatus.Contains("code 0x80070057") Then
lblDriveLockMsg.Text = "Drive selected is not Bit Locker encrypted"
ElseIf lockStatus.Contains("code 0x80070005") Then
lblDriveLockMsg.Text = "Drive selected is in use by an application on your machine, force dismounting might result in data loss, please check and close any applications using the drive"
Else
lblDriveLockMsg.Text = lockStatus
End If
myProcess.WaitForExit()
myProcess.Close()
End Sub

VB.NET - Problems trying to write a textfile

I have problems when trying to delete/create/write to this file.
The error:
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
The highlighted lines by debugger:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
(Any of two, if I delete one line, the other line takes the same error id)
The sub:
Public Sub C1Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not playerargs = Nothing Then
Dim Str As String
Dim Pattern As String = ControlChars.Quote
Dim ArgsArray() As String
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
objWriter.Close()
Next
End If
Next
If randomize.Checked = True Then
RandomiseFile(Temp_file)
End If
Process.Start(userSelectedPlayerFilePath, playerargs)
If autoclose.Checked = True Then
Me.Close()
End If
Else
MessageBox.Show("You must select at least one folder...", My.Settings.APPName)
End If
End Sub
First, File.Create creates or overwrite the file specified, so you don't need to Delete it before.
Second, initializing a StreamWriter as you do, blocks the file and therefore you can't recreate it after.
So, simply move the StreamWriter intialization after the File.Create, or better, remove altogether the File.Create and use the StreamWriter overload that overwrites the file
....
If Not playerargs = Nothing Then
....
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Using objWriter As New System.IO.StreamWriter(Temp_file, false)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
' objWriter.Close()
Next
End If
Next
End Using ' Flush, close and dispose the objWriter
....
Noticed also that you close the writer while still inside the loop, use the Using statement to close correctly the writer after the work is done.
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
That means the file is opened or been used by another process.
Open your task manager and check if the file is there, then close it or simplex end the process.
I have had the same issue but I got it solved by closing the file.
Hope this helps!
From your details it seems that you are willing to delete if file exists and creates a new one.
I would suggest to remove this line:
System.IO.File.Create(Temp_file)
and move this line just over the streamwriter line:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
Something like this would help you:
Partial code:
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
' Delete file if exists
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
' Create file for write.
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
...
...
...

Reading Console Output to write out an error log VB

I am running some commands on computers and I would like to have them output a seperate text file if the command cannot run.
For Each strUserName As String In strLines
Dim ReplaceCommand As String = sCommand.Replace("*", strUserName).Replace("$$$", saveFileDialog3.FileName & ".txt").Replace("###", exeSearch)
Shell("cmd.exe /c" & ReplaceCommand, AppWinStyle.Hide, True, )
' If Command Cannot Execute, List Why and Move onto Next Command
Using swrr As New StreamWriter(File.Open(ErrorLog, FileMode.OpenOrCreate))
If Console.Readline = "blahblah" Then swrr.WriteLine("FAIL") Else swrr.WriteLine("PASS")
End Using
Next
Am I on the right track? I am getting an output to a text file but its just one line ans always says PASS.
Several things: you're creating a new StreamWriter every time you want to write a line to it, instead of creating one then just writing to it when you need to. You're still using shell which is really basic, and not really suited for what you need. You should really be using a process for this.
I've written a function for you to use to execute the process instead of using the shell, which will return the output from the command execution to the ConsoleOutput variable, which you can then check for output strings.
Lastly, you should be using String.Format instead of replace to create the correct string for the command to run. For example:
Dim FirstName As String = "Jay"
Dim Age As String = "twenty"
Dim Greeting As String = String.Format("Hello {0}, I know you're {1} years old", FirstName, Age)
' Greetings value would be "Hello Jay, I know you're twenty years old"
So tweak the below to suit, specifically the Args variable, USING THE STRING.FORMAT function :)
Sub DoWork()
Dim ConsoleOutput As String = String.Empty
Using swrr As New StreamWriter(ErrorLog, True)
For Each strUserName As String In StrLines
ConsoleOutput = GetCMDOuput(strUserName, saveFileDialog3.FileName, exeSearch)
' If Command Cannot Execute, List Why and Move onto Next Command
If ConsoleOutput = "blahblah" Then swrr.WriteLine("FAIL") Else swrr.WriteLine("PASS")
Next
End Using
End Sub
Function GetCMDOuput(ByVal strUserName As String, ByVal strFileName As String, ByVal strExeSearch As String) As String
Dim Args As String = String.Format("/c -paramzero {0} -paramone {1} -paramtwo {2}", strUserName, strFileName, strExeSearch)
Dim CMD As New Process
CMD.StartInfo.FileName = "cmd.exe"
CMD.StartInfo.Arguments = Args
CMD.StartInfo.UseShellExecute = False
CMD.StartInfo.RedirectStandardInput = True
CMD.StartInfo.RedirectStandardOutput = True
CMD.StartInfo.CreateNoWindow = True
CMD.Start()
Dim retval As String = CMD.StandardOutput.ReadToEnd
CMD.WaitForExit()
Return retval
End Function