Monitoring a folder for new files in .net can easily be watched using the FileSystemWatcher in System.IO. You give it a path (ie: C:\toprint) and it will raise an event when a file is created (you can also watch for deleted, renamed and updated files).
Edit: I have new / full code here on GitHub.
I’ve had the need on several occasions to print new files as they are created, so the combination of the FileSystemWatcher and using a process to call the file and print work well together. Below the code to print to the default printer (works great for .pdf files):
c#:
Process PrintProcess = new Process(); PrintProcess.StartInfo.CreateNoWindow = false; PrintProcess.StartInfo.Verb = "print"; PrintProcess.StartInfo.FileName = e.FullPath; PrintProcess.Start();
vb:
Dim PrintProcess As New Process PrintProcess.StartInfo.CreateNoWindow = False PrintProcess.StartInfo.Verb = "print" PrintProcess.StartInfo.FileName = e.FullPath PrintProcess.Start()
The file watcher uses this syntax:
c#:
FileSystemWatcher fsWatcher = new FileSystemWatcher(txtDirToWatch.Text);
fsWatcher.Created += OnChanged;
var withFSW = fsWatcher; withFSW.EnableRaisingEvents = true; withFSW.IncludeSubdirectories = false; withFSW.WaitForChanged(WatcherChangeTypes.Created); withFSW.Filter = "*.pdf";
vb:
Dim fsWatcher As New FileSystemWatcher(txtDirToWatch.Text) AddHandler fsWatcher.Created, AddressOf OnChanged
With fsWatcher .EnableRaisingEvents = True .IncludeSubdirectories = False .WaitForChanged(WatcherChangeTypes.Created) .Filter = "*.pdf"
End With
And the OnChanged Event: c#:
public void OnChanged(object source, FileSystemEventArgs e) { //Do something with e.FullPath, etc. }
vb:
Public Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs) 'Do something with e.FullPath, etc. End Sub
*I haven’t used this method to print many different formats or tons of files at once, but give it a try!
If you’d like a fully working solution (vb or c#) drop me a line at chris.bitting(at)gmail(dot)com and I’d be glad to send my project and code.
[…] Watching & Printing New Files in a Directory – vb & c# […]
LikeLike
That was a great code which I took and created my own watcher in vb. I had an issue that every time I run the program, the very first file didn’t work as expected. The solution I found was to change the order of AddHandler and I put it before the the .waitForChange method. So my code looks like:
AddHandler fsWatcher.Created, AddressOf OnChanged
With fsWatcher
.EnableRaisingEvents = True
.IncludeSubdirectories = False
.Filter = “*.jpg”
.WaitForChanged(WatcherChangeTypes.Created)
End With
After that adjustment everything works like a charm!
Thank you for your code!
LikeLike