FileSystemWatcher is not working - vb.net

I added FileSystemWatcher in Form1_Load like this:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
....................
Dim watcher As New FileSystemWatcher()
'For watching current directory
watcher.Path = "/"
'For watching status.txt for any changes
watcher.Filter = "status.txt"
watcher.NotifyFilter = NotifyFilters.LastWrite
watcher.EnableRaisingEvents = True
AddHandler watcher.Changed, AddressOf OnChanged
End Sub
I have an OnChanged function which is a simple MessageBox. Still, when I change the status.txt file, no message box is shown.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim watcher As New IO.FileSystemWatcher()
'For watching current directory
watcher.Path = **System.IO.Directory.GetCurrentDirectory()** 'Note how to obtain current directory
watcher.NotifyFilter = NotifyFilters.LastWrite
'When I pasted your code and created my own status.txt file using
'right click->new->Text File on Windows 7 it appended a '.txt' automatically so the
'filter wasn't finding it as the file name was status.txt.txt renaming the file
'solved the problem
watcher.Filter = "status.txt"
AddHandler watcher.Changed, AddressOf OnChanged
watcher.EnableRaisingEvents = True
End Sub
Private Shared Sub OnChanged(ByVal source As Object, ByVal e As IO.FileSystemEventArgs)
MessageBox.Show("Got it")
End Sub
From http://bartdesmet.net/blogs/bart/archive/2004/10/21/447.aspx
You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example, if you use a FileSystemWatcher component to monitor the creation of new files in a directory, and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner. Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up

You should also listen for the Deleted event.
Depending on the editor you're using, they sometimes Delete/Replace the file instead of simply changing it.

Related

How do i link Visual Studio applications over LAN

I have created a VS application , I have installed a copy on another computer and I wish to link them via LAN so that if settings are canged in one , the others setings will also be saved .
for example this setting
i created a new name in the sttings are and call it "AdminIn" and set its type it integer , its scope to user and set its value to 0
Dim AI As New My .MySettings
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AI.AdminIn = AI.AdminIn + 1
Ai.SAve()
End Sub
now how can AI also be updated in the other application on the other computer .
How do I connect via LAN and accomplish this ?
I found this link that provides some example code to modify application-scoped variables from My.Settings that might be useful. I've tested it out with a simple form with a timer and a label showing me the current value of the AdminIn setting, and it seems to work. The timer updates the label on every instance of the form by checking the reloaded My.Settings value. The variable would need to be application scoped in order to be accessible to all users on any machine that may run the executable.
http://www.codeproject.com/Articles/19211/Changing-application-scoped-settings-at-run-time
Here's the form code that I put together to keep the current admin count up-to-date. Very simplistic, but it seems to do the job neatly.
Public Class Form1
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
'Decrement the AdminIn count when the current instance of the form is closed.
Me.tmrAdminCheck.Stop()
ChangeMyAppScopedSetting((My.Settings.AdminIn - 1).ToString)
'Reload the .exe.config file to synchronize the current AdminIn count.
My.Settings.Reload()
My.Settings.Save()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Increment the current AdminIn count when a new instance of the form is loaded
ChangeMyAppScopedSetting((My.Settings.AdminIn + 1).ToString)
'Reload the .exe.config file to synchronize the current AdminIn count.
My.Settings.Reload()
My.Settings.Save()
Me.lblAdminsIn.Text = "Current Admins In: " & My.Settings.AdminIn.ToString
'Start the timer to periodically check the AdminIn count from My.Settings
Me.tmrAdminCheck.Enabled = True
Me.tmrAdminCheck.Interval = 100
Me.tmrAdminCheck.Start()
Me.Refresh()
Application.DoEvents()
End Sub
Private Sub tmrAdminCheck_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrAdminCheck.Tick
'Reload the .exe.config file to synchronize the current AdminIn count.
My.Settings.Reload()
Me.lblAdminsIn.Text = "Current Admins In: " & My.Settings.AdminIn.ToString
Me.Refresh()
Application.DoEvents()
End Sub
End Class
I've found a couple of things with this method, and they relate to what others have already mentioned in their comments:
The application's .exe.config file must be in an accessible location (the CodeProject example defaults to the application's executable directory). Of course, you could save the settings to an INI file or some other configuration file in another shared directory and accomplish a similar thing, but this method uses the My.Settings.
You'll may want to do some additional checking for the possibility
of two people attempting to get in at exactly the same time. If
that happens, the configuration file will still be open and locked,
and the new AdminIn value won't be saved. The CodeProject example
doesn't have any exception handling, but you could easily work this
functionality into the exception handling by making a recursive call
to the Sub.
Otherwise, this seems to be a totally viable method of accomplishing what you're talking about.

Saving pdf document from webbrowser control

I'm navigating from webbrowser control to an url like this;
http://www.who.int/cancer/modules/Team%20building.pdf
It's shown in webbrowser control. What I want to do is to download this pdf file to computer. But I tried many ways;
Dim filepath As String
filepath = "D:\temp1.pdf"
Dim client As WebClient = New WebClient()
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(WebBrowserEx1.Url, filepath)
This one downloads a pdf but there is nothing in the file.
Also tried with
objWebClient.DownloadFile()
nothing changed.
I tried to show a save or print dialog;
WebBrowserEx1.ShowSaveAsDialog()
WebBrowserEx1.ShowPrintDialog()
but they didnt show any dialog. Maybe the last one is because it doesnt wait to load the the pdf into webbrowser completely.
When I try html files there is no problem to dowload, but in this .pdf file, I think I didn't manage to wait the file to be loaded as pdf into browser. This function(s);
Private Sub WaitForPageLoad(ByVal adimno As String)
If adimno = "1" Then
AddHandler WebBrowserEx1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
While Not pageReady
Application.DoEvents()
End While
pageReady = False
End If
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If WebBrowserEx1.ReadyState = WebBrowserReadyState.Complete Then
pageReady = True
RemoveHandler WebBrowserEx1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End If
End Sub
are not working for this situation. I mean it gets into infinite loop.
So anyone knows how to wait this to load pdf then save into computer.
you could test the URL when document completed fires and if its .pdf, then do the following then navigate back, for example.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowserEx1.Navigate("http://www.who.int/cancer/modules/Team%20building.pdf")
End Sub
Private Sub WebBrowserEx1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowserEx1.DocumentCompleted
If WebBrowserEx1.Url.ToString.Contains(".pdf") Then
Using webClient = New WebClient()
Dim bytes = webClient.DownloadData(WebBrowserEx1.Url.ToString) 'again variable here
File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.pdf"), bytes) 'save to desktop or specialfolder. to list all the readily available user folders
End Using
'WebBrowserEx1.goback() 'could send browser back a page as well
End If
End Sub
You will need to make the filename "TEST" as a variable instead of a static string or else you will overwrite the same file each time. Perhaps:
WebBrowserEx1.DocumentTitle.ToString & ".pdf"
instead, which would save the file as pdf named by the webpage title. Only problem there is if the page contains illegal characters (that windows doesnt let you save with) it will throw an exception so that should be handled.

Streamwriter will not save to FileName entered by User with Default var.FileName initiated - VB.NET

I am new here, and relatively new to VB.NET. I have a specific problem with getting my StreamWriter to work properly. One of the requirements of my project is to give the file a default name when the user clicks the Save button, which I have done by setting mysave.Filename = "MyLog.log". I call a new instance of my streamwriter trying to save to the filename specified by the user (mySave.Filename again), but every time, it saves to the default MyLog.log file. I have pasted my code below.
If someone could tell me how I can make sure the data is being saved to the value entered by the user for File name, that would be greatly beneficial. Also, I apologize for the code format, its not perfectly readable, but I'm trying to learn how to use the 4 space indents to my advantage!!
Thanks!
Imports System.IO
Public Class Form1
Dim Initial As String = "C:\Users\Brian Frick\Documents\Visual Studio 2010\Projects\HW5_Frick_Creator\HW5_Frick_Creator\bin\Debug" 'give variable for full path without log file
Dim Fullpath As String = "C:\Users\Brian Frick\Documents\Visual Studio 2010\Projects\HW5_Frick_Creator\HW5_Frick_Creator\bin\Debug\MyLog.log" 'give one path for full path
Dim filewriter As New StreamWriter(Fullpath, True)
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit() ' quit application
filewriter.Close()
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
Dim mySave As New SaveFileDialog
mySave.Filter = "LOG File (*.log)|*.log" 'set filter to .log
mySave.DefaultExt = "log" 'set default extension
mySave.InitialDirectory = Initial 'set default directory
mySave.FileName = "MyLog.log"
mySave.OverwritePrompt = True ' make sure to ask user if they want to over write
If mySave.ShowDialog() = DialogResult.OK Then
Dim filewriter As New StreamWriter(mySave.FileName, True)
filewriter.Close()
'filewriter = New StreamWriter(mySave.FileName, True)
'filewriter.Close() 'close filewriter to allow access to write directory
'Dim Stream As New StreamWriter(mySave.FileName, True) 'save file to path chosen by user in SaveDialog
'Stream.Close() ' Close stream to allow access to directory
' filewriter.Close()
Else
'dialog cancelled - no action
End If
filewriter.Close()
filewriter = New StreamWriter(Fullpath, True) 're initiate filewriter to be used in successive iterations through the program without error
End Sub
Private Sub SavingsDepositBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SavingsDepositBtn.Click
'write to file for SavDep
filewriter.WriteLine("SavDep")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub SavingsWithdrawBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SavingsWithdrawBtn.Click
'write to file for SavWith
filewriter.WriteLine("SavWith")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub CheckDepsotBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckDepsotBtn.Click
'write to file for CheckDep
filewriter.WriteLine("CheckDep")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub CheckWithdrawBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckWithdrawBtn.Click
'write to file for CheckWith
filewriter.WriteLine("CheckWith")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
End Class
the general way you are using the filewriter won't work, and there are some other serious issues like that there are two 'FileWriter' variables with overlapping scope.
for your save routine, you can't just re-instantiate your filewriter to point it to a different path. that will destroy all the data that had been in the underlying stream, so you are just saving nothing.
try caching the data in memory while the program is running, and don't create the stream until you are ready to write all the data to it, and it to a file, all in one go. your current approach makes it very hard to prevent leaking handles to the log files, so if the app crashes the user will have to reboot to release the write lock before they can run it again. look into the 'using' construct and 'Try... Finally'

Release file\folder lock when using drag\drop onto control

I'm trying to loop through a list of files to get the path and filename.
These files are dragged onto a datagrid:
Private Sub DataGridView1_DragDrop(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
Dim filenames As String() = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())
For Each File In filenames
If Array.IndexOf(SupportedFormats, System.IO.Path.GetExtension(File)) <> -1 Then
Frm = New FormRestore(ServerName, File)
Frm.Show()
While Frm.Visible
Application.DoEvents()
End While
End If
Next
End Sub
A child form is created that processes an action based on the path and file name.
until the loop is complete, the folder the files were dragged from is locked.
How would I get a list of the path and file names AND process each one without locking out the source folder?
(I'm using the while loop to process the file names sequentially, pausing between each one while maintaining UI response)
Thanks.
Try processing the files after the drag&drop event by calling BeginInvoke in the handler.

Error with code?

Hi can anyone tell me why the following dose not work:
(p.s I dont want the file to append upon clicking abutton just upon clicking the checkbox.
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
Dim FILE_NAME As String = "C:\RXF\log.txt"
'Adding items for AutoCAD 2006...
If CheckBox1.CheckState = CheckState.Checked Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine("module: 4FNV-67-5H")
objWriter.Close()
End If
End Sub
End Class
Not reproducible, even with your exact code as posted. This works perfectly fine for me, creating a text file in the specified location if one does not exist and appending the specified text to the end of the file.
The only thing I suggest is wrapping your StreamWriter object in a Using statement to ensure that its Dispose method always gets called, even if an exception is thrown (which is all the more likely when you're doing disk I/O). So, your existing code would simply change to:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
Dim FILE_NAME As String = "C:\RXF\log.txt"
''#Adding items for AutoCAD 2006...
If CheckBox1.CheckState = CheckState.Checked Then
Using objWriter as New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine("module: 4FNV-67-5H")
objWriter.Close()
End Using
End If
End Sub
Also, if you anticipate this method getting called a lot (i.e., the user clicking and unclicking and clicking the checkbox repeatedly), you might consider creating the StreamWriter object once and saving it as a private class-level variable, instead of creating and disposing of it each time the method is called. Then you just have to make sure that you dispose of it whenever your class (presumably the containing form) is disposed.