C# is one of the most popular languages today and there are many reasons for this. It has many qualities that make it suitable for development for users at most all levels. Let’s discuss how to efficiently use the AsEnumerable and AsQueryable in C# LINQ.
FileSystemWatcher Class implements to watch for changes in a specified directory. We can watch for changes in files and subdirectories of the specified directory. We can create a component to watch files on a local computer, a network drive, or a remote computer. FileSystemWatcher is perhaps the most important features in .NET used in the workplace today.
Binding File System
FileSystemViewModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
class FileSystemViewModel { public List<FileInfo> FilesCollection { get { string path = @"C:\MyFolder"; System.IO.DirectoryInfo di = new DirectoryInfo(path); return di.GetFiles().ToList(); } } } |
MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Loaded += new RoutedEventHandler(MainWindow_Loaded); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { this.DataContext = new FileSystemViewModel(); } } |
MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<Window x:Class="Binding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <ListBox Name="LstProduct" ItemsSource="{Binding FilesCollection}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=FullName}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> |
The Property FilesCollection has only get access, get can only read information from that private field and return it. But set can only write information in that private field. But in our scenario, we are accessing the Window’s File System, So, we can’t know when the Folder gets update i.e., File Add / Delete / Rename. So, the above View Model fails to update the UI in dynamic.
Let us see how to overcome this problem. The .NET Framework introduces a new feature as like watchdog to monitor the File System, its called as FileSystemWatcher Class under the namespace System.IO. Let us see how to implement
FileSystemWatcher Class
FileSystemViewModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
class FileSystemViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private List<FileInfo> _filesCollection = new List<FileInfo>(); public List<FileInfo> FilesCollection { get { return _filesCollection; } set { _filesCollection = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("FilesCollection")); } } public FileSystemViewModel() { UpdateCollection(); FileSystem_WatchDog(); } public void FileSystem_WatchDog() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"C:\MyFolder"; /* Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Watch all types of files. watcher.Filter = "*.*"; // Add event handlers. watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnRenamed); // Begin watching. watcher.EnableRaisingEvents = true; } private void OnChanged(object source, FileSystemEventArgs e) { UpdateCollection(); } private void OnRenamed(object source, FileSystemEventArgs e) { UpdateCollection(); } public void UpdateCollection() { string path = @"C:\MyFolder"; System.IO.DirectoryInfo di = new DirectoryInfo(path); FilesCollection = di.GetFiles().ToList(); } } |
FileSystemWatcher Class has four major property, they are
- Path
- NotifyFilter
- Filter
- Event Handlers
- Transaction Control Language
Path
It specifies the filesystem physical path to watch.
NotifyFilter
Specifies the type of changes to watch for in a file or folder. It supports the following Notification, they are
- Attributes
- CreationTime
- DirectoryName
- FileName
- LastAccess
- LastWrite
- Security
- Size
Filter
It’s used to determine what files are monitored in a directory. For example
- *.* – All files (default). An empty string (“”) also watches all files.
- *.txt – All files with a “txt” extension.
- My*.txt – All files with a “txt” extension only stats with “My”.
- M*a.txt – All files with a “txt” extension only stats with “M” and ends with “a”.
- MyData.txt – Watches only MyData.txt
- Jellyfish.jpg – Watches only Jellyfish.jpg
Event Handlers
It’s triggers the following events
- OnChanged – Raises the Changed event.
- OnCreated – Raises the Created event.
- OnDeleted – Raises the Deleted event.
- OnError – Raises the Error event.
- OnRenamed – Raises the Renamed event.
EnableRaisingEvents
The component will not watch the specified directory until the Path property has been set and EnableRaisingEvents is true.
Important Notes:
Please note the following when using the FileSystemWatcher class.
- Hidden files are not ignored.
- In some systems, FileSystemWatcher reports changes to files using the short 8.3 file name format. For example, a change to “LongFileName.LongExtension” could be reported as “LongFil~.Lon”.
- This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see Link Demands.
- The maximum size you can set for the InternalBufferSize property for monitoring a directory over the network is 64 KB.
- Running FileSystemWatcher on Windows 98 is not supported.
Conclusion :
This article targets at understanding how efficiently we can Bind File System in WPF using FileSystemWatcher in C#. This article is intended for the beginner/intermediate level. I hope, this post will solve all your basic functionality implementation of FileSystemWatcher in C#. Think Big… Start Small… Do Fast…