Search code examples
c#validationfile-exists

How to validate if a folder already exists


I want to create folders and add classes within the folders. I can create the folder once, but once I have created it, I just want to add classes. My code gives error because I'm trying to create a folder several times, which is not right. So before adding a class to the folder, I want to check if the folder already exists and if it exists I just want to add the class.

 ProjectItem rootFolder = project.ProjectItems.AddFolder(folder);                    
 ProjectItem item = rootFolder.ProjectItems.AddFromTemplate(itemPath, className);

Solution

  • According to documentation, there is no kind of Exists function which would tell us if a folder already existed.

    So you have at least two options:

    1. Try and ignore

    Simply:

    try 
    {
        var rootFolder = project.ProjectItems.AddFolder(folder);
    }
    catch 
    {
        /* folder already exists, nothing to do */
    }
    

    2. Solution folders can only occur in the first level below the solution root node, so we can get away with a non-recursive solution.

    public static bool CheckIfSolutionFolderExists(ProjectItems projectItems, string foldername)
    {
        foreach(var projectItem in projectItems)
        {
            if(projectItem.Kind == EnvDTE.vsProjectItemKindVirtualFolder)
            {
                if(projectItem.Name == foldername)
                {
                    return true;
                }
            }
        }
        return false;
    }
    

    For a recursive solution, I found this, which boils down to:

    public static bool CheckIfFileExistsInProject(ProjectItems projectItems, string fullpath)
    {
        foreach(ProjectItem projectItem in projectItems)
        {
            if(projectItem.Name == fullpath)
            {
                return true; 
            }
            else if ((projectItem.ProjectItems != null) && (projectItem.ProjectItems.Count > 0))
            {
                /* recursive search */
                return CheckIfFileExistsInProject(projectItem.ProjectItems, fullpath);
            }
        } 
        return false;
    }
    

    A robust pattern for solution and project folder management would use AddFromDirectory whenever you want to mirror the file system hierarchy in the project tree, and AddFolder only for virtual folders that have no representation in the file system.

    ProjectItem item;
    if(Directory.Exists(itemname))
    {
        item = project.AddFromDirectory(itemname);
    }
    else
    {
        item = project.AddFolder(itemname);
    }
    

    (source: inspired from this)