How to refresh OpenFileDialog .txt file in Label (VB)? - vb.net

My VB application should read text using a StreamReader and show the .txt file contents in a label:
Private Sub FileLocationButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FileLocationButton.Click
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
If OpenFileDialog1.FileName <> "" Then
Dim SR As New StreamReader(OpenFileDialog1.FileName)
Do Until SR.EndOfStream
Label6.Text = Label6.Text & SR.ReadLine & vbCrLf
Loop
SR.Close()
End If
End Sub
I am writing and saving the text file in MS Word etc. and would like to view the updated version of the file (the text) in the vb app.
Therefore:
I have added a timer and would like to know what code would allow the application to refresh the label with it's new text (from the .txt file) every 3 seconds so that the new content I just typed in MS Word/Notepad etc. will show?

You can use a timer to refresh the text in the label. In the form designer, drag a Timer from the toolbox onto your main form (Form1). Add a FilePath property to your preferences form (Preferences1) and use it to store the path selected in the OpenFileDialog. When you show the preferences form, save its path in a class level variable in the main form and start the timer with an interval of 3000 (this is milliseconds, so 3000 is 3 seconds). In the timer Tick event, read the file again and replace the text in the label. Note that the following code uses File.ReadAllText to read the file (and close it) in one statement.
In the main form (Form1) you have this code
Private textFile As String
Sub PrefButton_Click(sender As Object, e As EventArgs) Handles PrefButton.Click
Using pref As New Preferences1
pref.ShowDialog
textFile = pref.FilePath
End Using
If textFile <> "" Then Label6.Text = File.ReadAllText(textFile)
Timer1.Interval = 3000
Timer1.Start
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) _
Handles Timer1.Tick
If textFile <> "" Then Label6.Text = File.ReadAllText(textFile)
End Sub
In the preferences form (Preferences1) you have this code
Private myPath As String
Public ReadOnly Property FilePath As String
Get
Return myPath
End Get
End Property
Private Sub FileLocationButton_Click(sender As Object, e As EventArgs) _
Handles FileLocationButton.Click
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
myPath = OpenFileDialog1.FileName
End If
End Sub

Related

when the text in a textbox is equal to a certain word i need to value in the combo box to be saved for that text

I have orders in text files in the debug folder and when i type the name of the order in a text box it displays the order is a list box and there is a combo box underneath where i can change the status of the meal preparation (Being prepared, ready to deliver etc,). If i go back to that form and type in the same order name into the textbox i need to previous prepartion status to be already in the textbox. Thanks for any help!
Public Class frmOrderStatus
Private Sub btnStatus_Click(sender As Object, e As EventArgs) Handles btnStatus.Click
Dim sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
lstOrder.Items.Add(sr.ReadLine)
Loop
End Sub
Private Sub OrderStatus_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstOrder.Items.Clear()
btnStatus.Enabled = False
ChangeStatus.Enabled = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
strTxtOrderNum = txtOrderNum2.Text
btnStatus.Enabled = True
ChangeStatus.Enabled = True
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
strSaveStatus = ChangeStatus.SelectedIndex
End Sub
Private Sub ChangeStatus_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ChangeStatus.SelectedIndexChanged
End Sub
End Class
It recognizes the file; it just tells you it is in use. A Stream must be closed and disposed. I don't see the StreamReader even being closed let alone disposed. A `Using...End Using block will close and dispose of objects even if there is an error.
I just used a text file I happened to have to test.
Private strTxtOrderNum As String = "host"
Private Sub ReadFile()
Using sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
ListBox1.Items.Add(sr.ReadLine)
Loop
End Using
End Sub
Private Sub WriteFile()
Dim strSelectedItem = ComboBox1.Text
Using swVar As IO.StreamWriter = IO.File.AppendText(strTxtOrderNum & ".txt")
swVar.WriteLine(strSelectedItem)
End Using
End Sub

Open a ".exe" with a Button using a file path from a TextBox

I have a TextBox called TextBox1, which is filled by a Button that gets a file path using OpenFileDialog. I want a button (Button3) to start several processes one after another with an interval of 2 hours then close it and open the next one.
In total I have 4 different TextBoxes (TextBox1, TextBox2, TextBox3 and TextBox4) and 4 different file paths that I want to open with the same button with the interval I mentioned before.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:temp"
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox1.Text = OpenFileDialog1.FileName.ToString()
If Not (strm Is Nothing) Then
'insert code to read the file data
strm.Close()
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
OpenFileDialog2.Title = "Please Select a File"
OpenFileDialog2.InitialDirectory = "C:temp"
OpenFileDialog2.ShowDialog()
End Sub
Private Sub OpenFileDialog2_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog2.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog2.OpenFile()
TextBox3.Text = OpenFileDialog2.FileName.ToString()
If Not (strm Is Nothing) Then
'insert code to read the file data
strm.Close()
End If
End Sub
Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
End Sub
End Class
To launch a new process use:
dim myProcess = Process.start(filename)
You dont' need the code that does the following:
Dim strm As System.IO.Stream
strm = OpenFileDialog2.OpenFile()
If Not (strm Is Nothing) Then
strm.Close()
End If
This is opening the exe file as if it were trying to read the data from it.
Instead just use
dim process = Process.Start(OpenFileDialogX.Filename)
Note: your initial directory seems to be c:temp not c:\temp as it probably should be

Writing a text file into an array and reading a particular line VB

I am trying to output a specific line from a text file into an array, where each Button will produce a different line. For example Button1 should output the first line in the text file and Button2 should output the second line in the text file.
Text file:
Red
Blue
Orange
Green
When I press Button1 I get the first line in the TextBox ("Red") however when I press Button2 I still get "Red".
Code
Public Class Form1
Dim i As Integer
Dim character As String = ""
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
i = 0
readfile()
TextBox1.Text = TextBox1.Text + character
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
i = 1
readfile()
TextBox1.Text = TextBox1.Text + character
End Sub
Sub readfile()
Dim SR As New StreamReader("Colours.txt")
Dim Characters(3) As String
Do Until SR.Peek = -1
character = SR.ReadLine
Characters(i) = character
Loop
SR.Close()
End Sub
End Class
I suggest using File.ReadAllLines to read the lines text file into a String array in the form's Load event. Then your Button.Click events can just copy the required line into the TextBox.
Public Class Form1
Private lines() As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lines = IO.File.ReadAllLines("Colours.txt")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = lines(0)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = lines(1)
End Sub
End Class
In your question, it's not clear if you want to just store the selected line in the TextBox, or append the line to the TextBox. If you want to append, you can use TextBox1.Text &= lines(0) 'or lines(1) (using &= instead of =) although in that case, you probably also want to add some kind of separator.

Get files one at a time from a folder in VB.NET

I am trying to read some text files path in a folder sequentially. However, I get only the first file.
I need to get the first file, execute a timer, get the next file path, execute a timer right up to the last file in the folder, and stop. How can I get around this?
Private zMailbox As String = "c:\Fold\"
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Timer1.Tick
Dim finfo As New IO.DirectoryInfo(zMailbox)
For Each fi In finfo.GetFiles("*.txt")
TextBox1.Text = fi.FullName
Next
End Sub
Thanks to the contributions below I got the code to work with the text box value. However, it gives the index count instead of the path which I want to retrieve.
Private zMailbox As String = "c:\Fold\"
Dim files As FileInfo()
Dim index As Integer = 0
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Dim finfo As New IO.DirectoryInfo(zMailbox)
files = finfo.GetFiles("*.txt")
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Timer1.Tick
If index >= files.Length Then
index = 0
End If
TextBox1.Text = (ListBox1.Items.Add(files(index)))
index += 1
End Sub
Your code loads all the files in the Timer event and assign them to the TextBox1.Text property inside the loop. Every loop overwrites the data that has been written in the previous loop.
At the end of the loop you see only the last value.
To show sequentially the files inside the Timer Tick event, you need to read the directory content before starting the Timer in a global FileInfo array. Another global variable will be used as indexer to show a particular file from this FileInfo array in your Timer.Tick event.
The index will be incremented and, at the next Tick, you could show the next file
Dim files as FileInfo()
Dim index As Integer = 0
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim finfo As New IO.DirectoryInfo(zMailbox)
files = finfo.GetFiles("*.txt")
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
if index >= files.Length Then
index = 0
End If
TextBox1.Text = files(index)
index += 1
End Sub
EDIT
According to your comment, you need to set the MultiLine property of the TextBox to true (using the form designer) and then, at every Tick, instead of replacing the Text property, append to it
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
if index >= files.Length Then
return ' Reached the end of the array. Stop the Timer???
End If
TextBox1.AppendText(files(index) & Environment.NewLine)
index += 1
End Sub
As a side note, if you want to show all file names together then it is not clear why you need a timer at all.
You could get the same result with code like this
Dim finfo As New IO.DirectoryInfo(zMailbox)
Dim files = finfo.EnumerateFiles("*.txt")
TextBox1.Text = string.Join(Environment.NewLine, files.Select(Function(x) x.FullName).ToArray())
On the original code you posted you where getting all files in the for loop each time the timer clicks.
After reading steve answer, and your comments, probably you always got all the files, but you override the textbox.text value.
TextBox1.Text += < String > & vbNewLine
Where < String >, of course, is the string returned by DirectoryInfo.GetFiles()
I think steve answer works just fine, but you are not implementing it well.
I would try and make this as easy as possible for you. You Microsoft's Reactive Framework for this. Just NuGet "Rx-Main".
Here's what you can then do:
finfo.GetFiles("*.txt").ToObservable() _
.Zip(Observable.Interval(TimeSpan.FromSeconds(1.0)), Function(f, _) f.Name) _
.ObserveOn(TextBox1) _
.Subscribe(Function(n) textbox_text += n + Environment.NewLine)
That's it. No timers. No separate methods. No need for module-level variables. Just one line of code and you're done.
It's processed on a background thread and then marshalled back to the UI via the .ObserveOn(TextBox1) call.
You can even keep a reference to the IDisposable returned by the .Subscribe(...) call to terminate the observable (timer) early.
Simple.
This seems a bit Rube Goldberg-ish. Just get all the files and loop through them in your Button_Click method:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim finfo As New IO.DirectoryInfo(zMailbox)
For Each fi In finfo.GetFiles("*.txt")
TextBox1.Text = fi.FullName
Next
End Sub

It maybe inaccessible due to its protection level

I was trying to code a download manager but get this error:
'save' is not declared. It maybe inaccessible due to its protection level
Here is my code:
Imports System.Net
Public Class Form1
Private WithEvents httpclient As webClient
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ListBox1.Items.Add(TextBox1.Text)
TextBox1.Clear()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.ShowDialog()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Try
httpclient = New WebClient
Dim total As Integer = ListBox1.Items.Count
Dim current As Integer = -1
While current < total
ListBox1.SelectedIndex = current + 1
Dim download As String = ListBox1.SelectedItem
httpclient.DownloadFileAsync(New Uri(download), save)
Label3.Text = "Current Status: Downloading:..."
Do While httpclient.IsBusy
Application.DoEvents()
Loop
current = current + 1
End While
Catch ex As Exception
ListBox1.Items.Clear()
End Try
End Sub
End Class
DownloadFileAsync takes 2 parameters. The first is the URL of the file to download and the second is the local location to save the file. The tutorial you were following likely set the variable Save somewhere in the code.
To get this to work, you can replace it with something like "C:\Test.txt" to download it to that location or define the variable Save and set it's value to the location you want to save the file.
With your existing code, to allow a user to select the save location, you need to make the following changes. Declare the Save variable private to the form, under the Public Class Form1 line:
Private Save as string
Then in your Button1_Click event, it should look more like this:
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
Save = SaveFileDialog1.FileName
End If
Dim download As String = ListBox1.SelectedItem
httpclient.DownloadFileAsync(New Uri(download), "save")