Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Potatobob · Sep 17, 2016 at 07:43 PM · erroraccesspcdirectory

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 !

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image jaja1 · Sep 17, 2016 at 08:36 PM 1
Share

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.

1 Reply

· Add your reply
  • Sort: 
avatar image
1

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.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image jaja1 · Sep 23, 2016 at 12:08 AM 0
Share

plus 1 for explaining your solution to everybody. It always helps when a user solves their own problem AND posts their solution!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

67 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Access is denied in Windows 8 App 0 Answers

Getting a bunch of errors after the latest Unity update (Unity 3.8f1) 5 Answers

Build Error on PC!! HELP!!!! 1 Answer

Saving File in new directory - Unauthorized Access Exception 1 Answer

WebPlayer/Standalone crashes on PC but not on Mac 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges