0

I am using the following code to access 4 folders. However, there is 1 folder which is private and only seniors have access to it. How can I avoid that folder and still access the other 4 folders?

class Program
{
    const string FILENAME = @"H:\Personal\text.xml";
    const string FOLDER = @"F:\Apps";
    static XmlWriter writer = null;
    static void Main(string[] args)
    {
        XmlWriterSettings settings = new XmlWriterSettings
        {
            Indent = true
        };

        writer = XmlWriter.Create(FILENAME, settings);
        writer.WriteStartDocument(true);

        DirectoryInfo info = new DirectoryInfo(FOLDER);
        WriteTree(info);

        writer.WriteEndDocument();
        writer.Flush();
        writer.Close();
        Console.WriteLine("Enter Return");
        Console.ReadLine();
    }

EDIT: (WriteTree Code) I have added the rest of the code which also includes the WriteTree code. I do not have access to the management folder.

    static long WriteTree(DirectoryInfo info)
    {  
    long size = 0;
        writer.WriteStartElement("Folder");
        try
        {
            writer.WriteAttributeString("name", info.Name);
            writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
            writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
            writer.WriteAttributeString("date", info.LastWriteTime.ToString());


            foreach (DirectoryInfo childInfo in info.GetDirectories())
            {
                size += WriteTree(childInfo);
            }

        }
        catch (Exception ex)
        {
            string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
            Console.WriteLine(errorMsg);
            writer.WriteElementString("Error", errorMsg);
        }

        FileInfo[] fileInfo = null;
        try
        {
            fileInfo = info.GetFiles();
        }
        catch (Exception ex)
        {
            string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
            Console.WriteLine(errorMsg);
            writer.WriteElementString("Error", errorMsg);
        }

        if (fileInfo != null)
        {
            foreach (FileInfo finfo in fileInfo)
            {
                try
                {
                    writer.WriteStartElement("File");
                    writer.WriteAttributeString("name", finfo.Name);
                    writer.WriteAttributeString("size", finfo.Length.ToString());
                    writer.WriteAttributeString("date", info.LastWriteTime.ToString());
                    writer.WriteEndElement();
                    size += finfo.Length;
                }
                catch (Exception ex)
                {
                    string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
                    Console.WriteLine(errorMsg);
                    writer.WriteElementString("Error", errorMsg);
                }
            }
        }

        writer.WriteElementString("size", size.ToString());
        writer.WriteEndElement();
        return size;

    }
  }
 }

Error: Exception Folder: Error: Access to the path is denied.

  • Show code of WriteTree method – Evgeny Gorbovoy Mar 19 '18 at 09:31
  • 1
    You can wrap the folder/file access in a try...catch block to gracefully fail in the cases the user has no access to the folder. – Fabulous Mar 19 '18 at 09:33
  • Using `try catch` to log error folders, and continue on the others folders? – Steven Chou Mar 19 '18 at 09:33
  • Also if it's an option for you, your app can request elevated privileges so that it has access to the necessary folder at run time. – Fabulous Mar 19 '18 at 09:34
  • We need to see the `WriteTree` method, this is presumably where the error occurs. You might be able to `try ... catch` or you could have a list of excludes. – Ashley Medway Mar 19 '18 at 09:35
  • First of all remove all catch(Exception) or catch{}. Catch only those exceptions you expect to get. For example, catch(UnauthorizedAccessException) as posted by @EFAV – Evgeny Gorbovoy Mar 19 '18 at 09:58

1 Answers1

2

You could check the permissions before write the file with richardwiden's answer : Checking for directory and file write permissions in .NET

Or you could use try catch in your WriteTree() function to ignore the UnauthorizedAccessException exception like :

try {
    writer.WriteAttributeString("name", info.Name);
    [...]
} catch (Exception ex) {
    // If is a permission error, ignore exception
    if (ex is UnauthorizedAccessException)
         return size;

    // custom error log
    string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
    Console.WriteLine(errorMsg);
    writer.WriteElementString("Error", errorMsg);
}
EFAV
  • 61
  • 5
  • 1
    Catch exactly on method you expect it: writer = XmlWriter.Create(FILENAME, settings); writer.WriteStartDocument(true); DirectoryInfo info = null; try { info = new DirectoryInfo(FOLDER); } catch(UnauthorizedAccessException e){} if(info!=null) WriteTree(info); writer.WriteEndDocument(); writer.Flush(); writer.Close(); Otherwise you can get execption from XmlWriter.Create for example, which is not related to directory access – Evgeny Gorbovoy Mar 19 '18 at 09:44
  • Are you sure is `new DirectoryInfo(FOLDER);` which make the exception ? Maybe it is `WriteTree(info)` function ... – EFAV Mar 19 '18 at 09:47
  • I checked DirectoryInfo.ctor - it does not throw UnauthorizedAccess. So as you said it is necessary to wrap only writetree method. Btw, where did you get information about UnauthorizedAccessException - could you please post it in too – Evgeny Gorbovoy Mar 19 '18 at 09:51
  • I +ed your post, but he added WriteTree to original question. Everything became useless now) – Evgeny Gorbovoy Mar 19 '18 at 09:56
  • @Sim Yes you already use a try catch in `WriteTree` function. I updated my answer – EFAV Mar 19 '18 at 13:35
  • @EFAV that worked! However its only displaying that theres 6 folders. It doesn't mention the subfolders anymore! –  Mar 19 '18 at 14:00
  • @Sim So you have another problem in your algorithm. Adding only this two lines `if (ex is UnauthorizedAccessException) return size;` should not change your program behavior. Make a new topic if needed and feel free to accept my answer checking the green tick. Thnaks – EFAV Mar 19 '18 at 14:07