Access to the path is denied when using Directory.GetFiles(...)
If you want to continue with the next folder after a fail, then yea; you'll have to do it yourself. I would recommend a Stack<T>
(depth first) or Queue<T>
(bredth first) rather than recursion, and an iterator block (yield return
); then you avoid both stack-overflow and memory usage issues.
Example:
public static IEnumerable<string> GetFiles(string root, string searchPattern)
{
Stack<string> pending = new Stack<string>();
pending.Push(root);
while (pending.Count != 0)
{
var path = pending.Pop();
string[] next = null;
try
{
next = Directory.GetFiles(path, searchPattern);
}
catch { }
if(next != null && next.Length != 0)
foreach (var file in next) yield return file;
try
{
next = Directory.GetDirectories(path);
foreach (var subdir in next) pending.Push(subdir);
}
catch { }
}
}
Ignore folders/files when Directory.GetFiles() is denied access
You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):
using System;
using System.IO;
static class Program
{
static void Main()
{
string path = ""; // TODO
ApplyAllFiles(path, ProcessFile);
}
static void ProcessFile(string path) {/* ... */}
static void ApplyAllFiles(string folder, Action<string> fileAction)
{
foreach (string file in Directory.GetFiles(folder))
{
fileAction(file);
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
ApplyAllFiles(subDir, fileAction);
}
catch
{
// swallow, log, whatever
}
}
}
}
When using Directory.GetFiles(…) , I get exception Access to the path is denied
Your @"\\10.2.10.2\...
path would refer to the root of the current drive, that shouldn't be.
You need :
string VideosPath = Server.MapPath("~/10.2.10.2/...");
...
where ~/
is the root of your app and just /
would be the root of the 'site'
How to ignore Access to the path is denied / UnauthorizedAccess Exception in C#?
Best way to do this is to add a Try/Catch block to handle the exception...
try
{
string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
return filenames;
}
catch (Exception ex)
{
//Do something when you dont have access
return null;//if you return null remember to handle it in calling code
}
you can also specifically handle the UnauthorizedAccessException if you are doing other code in this function and you want to make sure it is an access exception that causes it to fail (this exception is thrown by the Directory.GetFiles function)...
try
{
//...
}
catch(UnauthorizedAccessException ex)
{
//User cannot access directory
}
catch(Exception ex)
{
//a different exception
}
EDIT: As pointed out in the comments below it appears you are doing a recursive search with the GetFiles function call. If you want this to bypass any errors and carry on then you will need to write your own recursive function. There is a great example here that will do what you need. Here is a modification which should be exactly what you need...
List<string> DirSearch(string sDir)
{
List<string> files = new List<string>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files;
}
Access to file is denied
As per Directory.GetFiles, the error UnauthorizedAccessException is caused by the following:
The caller does not have the required permission.
Also, I wouldnt run GetFiles with search option as AllDirectories but go through one directory at a time. I used this link:
UnauthorizedAccessException cannot resolve Directory.GetFiles failure
Answer 2 (not the accepted one)
UnauthorizedAccessException cannot resolve Directory.GetFiles failure
In order to gain control on the level that you want, you should probably probe one directory at a time, instead of a whole tree. The following method populates the given IList<string>
with all files found in the directory tree, except those where the user doesn't have access:
// using System.Linq
private static void AddFiles(string path, IList<string> files)
{
try
{
Directory.GetFiles(path)
.ToList()
.ForEach(s => files.Add(s));
Directory.GetDirectories(path)
.ToList()
.ForEach(s => AddFiles(s, files));
}
catch (UnauthorizedAccessException ex)
{
// ok, so we are not allowed to dig into that directory. Move on.
}
}
GetFiles Access Denied Exception
When an exception occurs and you catch the exception, you still need to return a result for the function. Initialize your variable files to contain an empty array and then return it after the try-catch-block, so it is always returned, even when an error occurs.
public string[] passFiles(string location)
{
// Create an empty array that will be returned in case something goes wrong
string[] files = new string[0];
try
{
files = Directory.GetFiles(location);
}
catch (UnauthorizedAccessException)
{
// Code here will be hit if access is denied.
}
return files;
}
See also this question for a similar question and some useful answers.
System.UnauthorizedAccessException when executing DirectoryInfo().GetFiles() from W3WP - Why?
It seems that you have a "double-hop" problem.
When you authenticate to the IIS server is the first 'hop'.
When IIS tries to access UNC, is the second hop which is not allowed.
IIS cannot in turn pass on your credentials to the UNC.
For more infos see this articles
UNC Path Access Denied error
Double Hop Problem
UnauthorizedAccessException when using Directory.GetFiles
Catch the exception, ignore it, and move on to the next directory.
Related Topics
Find a Control in Windows Forms by Name
Sorting a List Using Lambda/Linq to Objects
Regex to Strip Line Comments from C#
Splitting a String/Number Every Nth Character/Number
Task Parallel Library Replacement for Backgroundworker
Why Should I Use Int Instead of a Byte or Short in C#
How to Get More Than 1000 Records from a Directorysearcher
Deserialize a JSON Array in C#
C# Image Resizing to Different Size While Preserving Aspect Ratio
Embedding Assemblies Inside Another Assembly
.Net: Determine the Type of "This" Class in Its Static Method
Sqlite Database Locked Exception
System.Text.JSON API Is There Something Like Icontractresolver