0

Long version:

I've been asked to develop a program which write files in a directory into a database. Also the files which are on deeper levels in that directory needs to be written to the database. There it should be displayed with two columns. One shows the path, the other one shows the filename + extension. I wrote a program working just fine in the test environment. However, in the live environment, I don't have all the rights and permissions to open every single directory I want. Also, due to some migrations, several directories got too long path names, and can't be opened anymore. So they told me to write those directories into the database, but instead of showing in the file_name column the file name and extension, to fill that one with "No access". However, to avoid trying to open 'bad' directories, I used a try/catch module. Now I need a variable declared in try and use it in catch. Is there anyway this is possible to do? I will post a part of the code so you can see what I have at this moment.

Short version:

I want to take a variable declared in the try module and use it in the catch module. Is there any way to do that?

    public HashSet<String> getFolders(Path path, HashSet<String> folders)
    {                
    try
        {
            foreach (String folder in Directory.GetDirectories(path.getOrigineleMap()))
            {
                Path p = path;
                p.setOrigineleMap(folder);
                folders.Add(folder);
                getFolders(p,folders);
            }
        }
        catch (System.Exception e)
        {
            Console.WriteLine("No access to a folder");
            writeToDatabase(path, folder + @"\No access");   //path is a variable of the type Path, and the String should be the entire
        }                                                    //path from the directory + \No Access
        return folders;
    }
F. Koelman
  • 31
  • 6
  • 7
    You will have to create a variable outside of the try block, assign the value to that and then you will be able to access it in the catch block – JayV Jun 08 '18 at 13:56
  • Consider using the `Try{ } catch() { }` in your `foreach` loop to avoid quitting the loop if an exception is thrown. Bonus: You can access the `folder` variable in the `catch()` block. – croxy Jun 08 '18 at 14:03
  • Thanks for the comments. I tried to make a dummy string, where I assigned the value of folder to, so I could write that in the catch. Unfortunately, it seems that if I assign a value in the try, but the try isn't successful, that value gets unassigned. Also, because the error occurred in the foreach loop, I couldn't leave that out of the try/catch. I solved it by assigning an int, which I did +1 every time the try was successful. Then, in the catch, I made a List with the values of the HashSet, and got the index of that list. That way, I found the directory I was looking for. – F. Koelman Jun 11 '18 at 08:12

0 Answers0