I want to know how to find out the top level directory parent of a file (which resides under "My Drive"). Files are stored under multi-level sub-folders.
Since I have the same file stored in multiple places, I want to make sure that the source of the file that I am picking up is the right one. I have made a really dirty hack, which is time consuming which looks like this:
function start() {
var files = DriveApp.searchFiles("(title contains 'Worksheet')");
while (files.hasNext()) {
var file = files.next();
var fileName = file.getName();
var whichParents = getAllParents(file);
// process whichParents to use indexOf to look for a substring in retStr and move forward.
}
function getAllParents(file) {
var retStr="";
try{
var folder;
var parents = file.getParents();
while(1) {
while (parents.hasNext()) {
var parent = parents.next();
folder=parent;
retStr = retStr + parent.getName() + "->";
if(parent.getName() == "My Drive")
throw Exception;
}
parents = folder.getParents();
}
}
catch(e){
return retStr;
}
}
I have looked through StackExchange for quite some time to figure out why an exception is generated, to no avail. Appreciate any help on this!
while(1)
? This will cause an error. Is that the exception that you mentioned?