- Home /
How to verify if a file is accessible or if it is denied before throwing an error.
Hi , I have a very simple script that let me navigates folders at runtime for PC.
Although I have an issue when attempting to open folders that are not accessible.
NOTE: I don't want to open those files, if I don't have the access to them. All I need is to pass a 'IF' to verify if the the folder can be opened or not.
Here is what I have tried :
string[] myFiles = Directory.GetFiles(myPath);
Although it gives me this error:
UnauthorizedAccessException: Access to the path "C:/Users/Default User" is denied.
So to make this super clear, I DO NOT WANT THIS ERROR TO TRIGGER, I want only want to open the file if it can be done.
Thank you a lot !
Try this answer http://stackoverflow.com/questions/13954630/how-to-handle-unauthorizedaccessexception-when-attempting-to-add-files-from-loca
GetFiles is not the way to go...even if you try a recursive method.
Answer by Potatobob · Sep 18, 2016 at 02:03 PM
Thank you very much @jaja1 , this works just as expected !
It took me a while to make it work as I am really not that advanced in programming.
So for anyone with a similar issue (That doesn't understand well the other given answers) I wanted to link my changes to that series of answers. The main reason is that none of the code displayed by the other user shows what we should be using to make the code work.
Ex: Using System.Linq is not showing in the other answers but its required ...
This is the script I added to my asset folder , not on any gameobject since its not required that way. The script as only been modified a bit in order to show what we are 'Using' and fixed some stuff that got updated on unity5 version
using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System;
using System.Linq;
public class CheckIfAccessIsRequired : IEnumerable<FileSystemInfo>
{
/// <summary>
/// Starting directory to search from
/// </summary>
private DirectoryInfo root;
/// <summary>
/// Filter pattern
/// </summary>
private string pattern;
/// <summary>
/// Indicator if search is recursive or not
/// </summary>
private SearchOption searchOption;
/// <summary>
/// Any errors captured
/// </summary>
private IList<Exception> errors;
/// <summary>
/// Create an Enumerator that will scan the file system, skipping directories where access is denied
/// </summary>
/// <param name="root">Starting Directory</param>
/// <param name="pattern">Filter pattern</param >
/// <param name="option">Recursive or not</param>
public CheckIfAccessIsRequired(string root, string pattern, SearchOption option)
: this(new DirectoryInfo(root), pattern, option)
{}
/// <summary>
/// Create an Enumerator that will scan the file system, skipping directories where access is denied
/// </summary>
/// <param name="root">Starting Directory</param>
/// <param name="pattern">Filter pattern</param>
/// <param name="option">Recursive or not</param>
public CheckIfAccessIsRequired(DirectoryInfo root, string pattern, SearchOption option)
: this(root, pattern, option, new List<Exception>())
{}
// Internal constructor for recursive itterator
private CheckIfAccessIsRequired(DirectoryInfo root, string pattern, SearchOption option, IList<Exception> errors)
{
if (root == null || !root.Exists)
{
throw new ArgumentException("Root directory is not set or does not exist.", "root");
}
this.root = root;
this.searchOption = option;
this.pattern = String.IsNullOrEmpty(pattern)
? "*"
: pattern;
this.errors = errors;
}
/// <summary>
/// Errors captured while parsing the file system.
/// </summary>
public Exception[] Errors
{
get
{
return errors.ToArray();
}
}
/// <summary>
/// Helper class to enumerate the file system.
/// </summary>
private class Enumerator : IEnumerator<FileSystemInfo>
{
// Core enumerator that we will be walking though
private IEnumerator<FileSystemInfo> fileEnumerator;
// Directory enumerator to capture access errors
private IEnumerator<DirectoryInfo> directoryEnumerator;
private DirectoryInfo root;
private string pattern;
private SearchOption searchOption;
private IList<Exception> errors;
public Enumerator(DirectoryInfo root, string pattern, SearchOption option, IList<Exception> errors)
{
this.root = root;
this.pattern = pattern;
this.errors = errors;
this.searchOption = option;
Reset();
}
/// <summary>
/// Current item the primary itterator is pointing to
/// </summary>
public FileSystemInfo Current
{
get
{
//if (fileEnumerator == null) throw new ObjectDisposedException("FileEnumerator");
return fileEnumerator.Current as FileSystemInfo;
}
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
Dispose(true, true);
}
private void Dispose(bool file, bool dir)
{
if (file)
{
if (fileEnumerator != null)
fileEnumerator.Dispose();
fileEnumerator = null;
}
if (dir)
{
if (directoryEnumerator != null)
directoryEnumerator.Dispose();
directoryEnumerator = null;
}
}
public bool MoveNext()
{
// Enumerate the files in the current folder
if ((fileEnumerator != null) && (fileEnumerator.MoveNext()))
return true;
// Don't go recursive...
if (searchOption == SearchOption.TopDirectoryOnly) { return false; }
while ((directoryEnumerator != null) && (directoryEnumerator.MoveNext()))
{
Dispose(true, false);
try
{
fileEnumerator = new CheckIfAccessIsRequired(
directoryEnumerator.Current,
pattern,
SearchOption.AllDirectories,
errors
).GetEnumerator();
}
catch (Exception ex)
{
errors.Add(ex);
continue;
}
// Open up the current folder file enumerator
if (fileEnumerator.MoveNext())
return true;
}
Dispose(true, true);
return false;
}
public void Reset()
{
Dispose(true,true);
// Safely get the enumerators, including in the case where the root is not accessable
if (root != null)
{
try
{// Removed this part :" , SearchOption.TopDirectoryOnly " that was after pattern
fileEnumerator = root.GetFileSystemInfos(pattern).AsEnumerable<FileSystemInfo>().GetEnumerator();
}
catch (Exception ex)
{
errors.Add(ex);
fileEnumerator = null;
}
try
{// Removed this part :" , SearchOption.TopDirectoryOnly " that was after pattern
directoryEnumerator = root.GetDirectories(pattern).AsEnumerable<DirectoryInfo>().GetEnumerator();
}
catch (Exception ex)
{
errors.Add(ex);
directoryEnumerator = null;
}
}
}
}
public IEnumerator<FileSystemInfo> GetEnumerator()
{
return new Enumerator(root, pattern, searchOption, errors);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
THEN you can use this as a function (on the script of your choice) just like this:
string path = Application.dataPath; //just choose a path , application.datapath is my example of a simple path.
CheckIfAccessIsRequired myAccess = new CheckIfAccessIsRequired(path,"",System.IO.SearchOption.TopDirectoryOnly);
if (myAccess.GetEnumerator().MoveNext())
{
//your code for when the "path" can be accessed.
}
else
{
//your code for when the "path" would cause an error if you attempt to open it
}
Finally, I call the function CheckIfAccessIsRequired() with the second parameter set to empty as I have no clue how to use patterns and , leaving it blank sets it to the default so I don't worry about it.
The code I modified was from the answer jaja1 shared that lead me to this page.
plus 1 for explaining your solution to everybody. It always helps when a user solves their own problem AND posts their solution!
Your answer
![](https://koobas.hobune.stream/wayback/20220612093005im_/https://answers.unity.com/themes/thub/images/avi.jpg)