How can I do something after Process.Start("explorer.exe", OpenFolder) - vb.net

I have the following code that simply opens up a folder with txt files.
Private Sub OpenTabpageTextFolderToolStripMenuItem_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles OpenTabpageTextFolderToolStripMenuItem.Click
Dim OpenFolder = (RootDrive & "QuickEmailer2\TabTxt")
Process.Start("explorer.exe", OpenFolder)
End Sub
The user then edits a txt file, and closes.
I would like to call my refresh code and make use of the changes to the txt file, but if I put the call after process.start, it runs without waiting?
I could use code to do these edit, but there are 80 files to choose from and they only need edit them once (or twice) when setting up the program for the first time.
I am sure a bit of code that says:
Private Sub OpenTabpageTextFolderToolStripMenuItem_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles OpenTabpageTextFolderToolStripMenuItem.Click
Dim OpenFolder = (RootDrive & "QuickEmailer2\TabTxt")
Process.Start("explorer.exe", OpenFolder)
'**I will hang on here while you do your stuff, then I will continue...**
Call RefreshfromAllTxtFiles()
End Sub

alternative solution: use 2 buttons/steps to setting up the program for the first time!
button/step #1: open setup files
button/step #2: setup files modified... PROCEED!

Along the lines of Steve's comment, you can use a FileSystemWatcher to monitor changes to the directory. Something like this can get you started:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim fsw As FileSystemWatcher
fsw = New System.IO.FileSystemWatcher()
'this is the folder we want to monitor
fsw.Path = "c:\temp"
fsw.NotifyFilter = IO.NotifyFilters.Attributes
AddHandler fsw.Changed, AddressOf IveBeenChanged
fsw.EnableRaisingEvents = True
End Sub
Private Sub IveBeenChanged(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
'this displays the file that changed after it is saved
MessageBox.Show("File " & e.FullPath & " has been modified")
' you can call RefreshfromAllTxtFiles() here
End If
End Sub

Related

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

Button that opens Application Path + specific folder

I'm kind of confused on how to do this. What I want to do is when I click Button1, my program will open a folder in Explorer, and the second button will open a file as a text file.
Here's my code:
Button 1
Process.Start("explorer.exe", Application.ExecutablePath + "\mvram.biz")
Button 2
Process.Start("Notepad.Exe", "README.txt")
My problem is everytime I click the button it will open My Documents. It must open the APPpath+Specific Folder.
EDIT:
Public Class Form1
Private Sub ExcisionButtonDefault5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault5.Click
Me.Close()
End Sub
Private Sub ExcisionButtonDefault1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault1.Click
Dim path As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\mvram.biz\"
Process.Start("explorer.exe", path)
End Sub
Private Sub ExcisionButtonDefault2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault2.Click
Process.Start("explorer.exe", Application.StartupPath & "\Documents")
End Sub
Private Sub ExcisionButtonDefault3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault3.Click
Process.Start("Notepad.Exe", "/select," & "README.txt")
End Sub
Private Sub ExcisionButtonDefault4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault4.Click
Process.Start("explorer.exe", System.Windows.Forms.Application.StartupPath + "\Presentation")
End Sub
Private Sub ExcisionButtonDefault6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault6.Click
System.Diagnostics.Process.Start("http://www.mvram.biz")
End Sub
End Class
The reason why it opens a random location is because you are intending to execute a wrong path (whole app path + other app). You have to choose the directory. Try this code:
Dim path As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\mvram.biz"
Process.Start("explorer.exe", path)
Other option:
Dim path As String = Environment.CurrentDirectory & "\mvram.biz"
I personally prefer to use absolute paths rather than relative ones (just the name of the file when referring to the same directory).
To open a specific folder in FileExplorer, you can try passing this argument:
Dim x as string = "FolderPath"
Process.Start("explorer.exe", "/root,x")
Or you could pass the argument "/select,x", which will open File Explorer with the folder selected, but not opened. This article may be helpful. Or you can just have the file address, like you tried above, and it will open to the correct location.
And then to open a txt file, all you need to do is:
Process.Start("FileAddress")
This will open the file in its default editor.
HTH

Converting drag and drop application that shows directory into showing hash

I am having trouble converting this code into allowing me to drop files into my application and my application create a message box saying its md5 hash code. Currently, I have the code to give the directory of the file I dropped in.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.AllowDrop = True
End Sub
Private Sub Form1_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
MsgBox(path)
Next
End Sub
Private Sub Form1_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
End Class
Seems like you have most of the code you need, only needs a function to calculate the md5, and then you can plug that into your message box:
MsgBox(ComputeMD5Hash(path))
Here is the function, taken mostly from this Microsoft Support Article
Private Function ComputeMD5Hash(ByVal path As String) As String
Dim tmpSource() As Byte
Dim tmpHash() As Byte
'Create a byte array from source data.
tmpSource = My.Computer.FileSystem.ReadAllBytes(path)
'Compute hash based on source data.
tmpHash = New Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(tmpSource)
Dim i As Integer
Dim sOutput As New System.Text.StringBuilder(tmpHash.Length)
For i = 0 To tmpHash.Length - 1
sOutput.Append(tmpHash(i).ToString("X2"))
Next
Return sOutput.ToString()
End Function
In-case you want to drop a directory and get all the hashes of the files inside you first need to check if you're dealing with a file or a folder, if its a folder you loop over all the files inside and call the function for each one, which would make your DragDrop event handler look something like this, and have the added benefit both files and folders can be taken care of.
Private Sub Form1_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
If IO.File.GetAttributes(path) = FileAttribute.Directory Then
'Dealing with a Directory
Dim di As New IO.DirectoryInfo(path)
Dim fiArr As IO.FileInfo() = di.GetFiles()
Dim fri As IO.FileInfo
For Each fri In fiArr
MessageBox.Show(fri.FullName & " " & ComputeMD5Hash(fri.FullName))
Next fri
Else
'Dealing with a File
MessageBox.Show(path & " " & ComputeMD5Hash(path))
End If
Next
End Sub

Move Files using Kill in Visual Basic

I am making a desktop cleaner and I want the program to search For files extensions and move them into a new folder each named after the extension name. Here is what I have.
Public Class Form2
Private Sub Form_Load()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim MyFolderBrowser As New System.Windows.Forms.FolderBrowserDialog
Dim dlgResult As DialogResult = MyFolderBrowser.ShowDialog()
Me.FileReference.Text = MyFolderBrowser.SelectedPath
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Label1.Text = "Cleaned."
If CheckBox1.Checked = True Then
On Error Resume Next
Kill(Me.FileReference.Text("\*.txt"))
If Not Directory.Exists(FileReference.Text) Then
Directory.CreateDirectory(FileReference.Text)
End If
End If
End Sub
End Class
I want to use Kill(Me.FileReference.Text("\*.txt")) to move the files with .txt extention in the Directory which the textbox named Filereference.text contains which is extracted using MyFolderBrowser.SelectedPath.
How can I do this?
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
FileIO.SearchOption.SearchAllSubDirectories, "*.*")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.MoveFile(foundFile, "C:\StorageDir\" & foundFileInfo.Name)
Next

Adding a string to visual basic form

How can I add a string to my visual basic form?
I'm creating a study application for myself and this is what I have:
Imports System.Diagnostics
Public Class Form1
Dim amounts As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Processes.Tick
Dim proc() As Process = Process.GetProcesses
Dim newproc As New Process
amounts = 0
For Each newproc In proc
If newproc.ProcessName = "firefox" Then
newproc.Kill()
amounts = +1
Else
End If
Next
End Sub
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
End Sub
End Class
I'm trying to display a line of text on my form saying.. "Prevented firefox from running X times.
X being my "amounts" variable.
Here's what my form looks like: http://img696.imageshack.us/img696/8162/programq.png
So how can I put my amounts variable in place of the X?
Assuming that you have a label named yourLabel:
''# my personally preferred way
yourLabel.Text = String.Format("Prevented FireFox from running {0} times", _
amounts)
''# straight-forward concatenation
yourLabel.Text = "Prevented FireFox from running " & amount & " times"
''# using String.Concat (which is what the above code will be compiled to)
yourLabel.Text = String.Concat("Prevented FireFox from running ",amount," times")
Just try it
msgbox("Prevented FireFox from running " & amount & " times")