I've been trying to list all files located on my main drive in a console application but I keep getting the UnauthorizedAccessException.
Here is my code:
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
try
{
foreach(string file in Directory.GetFiles(@"C:/", "*", SearchOption.AllDirectories))
{
Console.WriteLine(file);
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}`
Here is the exception message:
Access to path 'C:\$Recycle.Bin\S-1-5-18' is denied.
I have tried to avoid to exception like so:
if (!file.Contains("RECYLCE") && !file.Contains("Recycle"))
{
Console.WriteLine(file);
}
Help would be appreciated. I need a way to skip the exception and carry on listing the rest of the files.
It looks like you're new here. If you want to get involved, click one of these buttons!