-
Notifications
You must be signed in to change notification settings - Fork 4
File Safety Checking Option
What is File Safety Checking Option? and why is it so important? Well, this is so important if you're insisted on using result of traversal to do IO operations. By default, it does secure traversal by not allowing single exception being thrown when you hit unauthorized access folder. But, for files, the result is not guaranteed to be used safely for IO operations. You must handle them by yourself. By specifying fileSafetyChecking parameter to true, you'll get totally secure result that is ready for IO operations. Keep in mind that this mechanism only works for NTFS file system where there is a security feature called access control that allows you to set specific access level for certain users. This mechanism only be found at .NET Framework version, so you won't find it within System.IO.SafeTraversal.Core namespace.
So, that sounds great! But, wait.. What is the downside? Well, because it must do double checking than the others, this feature results in slower performance. But, the good news is the difference is minor and you can use the result directly without worrying deny-access error.
- Reference all the required names.
using System.IO;
//For .NET Framework only
using System.IO.SafeTraversal;- To use instance error logging functionality, instantiate SafeTraversal class inside a method or as a global variable and subscribe its event within method or constructor
SafeTraversal safeTraversal = new SafeTraversal();
safeTraversal.LogError += (e, v) => WriteLine($"Error=`{v.ErrorMessage}`");- Let's define the path that we would like to traverse as a global variable.
private readonly static string PATH_ONE = @"E:\sample data";- Traverse top level files
//files
foreach (string file in safeTraversal.TraverseFiles(PATH_ONE, true))
{
//process result here
}
//or
foreach (string file in safeTraversal.TraverseFiles(PATH_ONE, true, SearchOption.TopDirectoryOnly))
{
//process result here
}
//or
foreach (FileInfo file in safeTraversal.TraverseFiles(new DirectoryInfo(PATH_ONE), true, SearchOption.TopDirectoryOnly))
{
//process result here
}- Traverse all level files
foreach (string file in safeTraversal.TraverseFiles(PATH_ONE, true, SearchOption.AllDirectories))
{
//process result here
}The remainder of its use will be same. Just specifying false/true for fileSafetyChecking option.