/// <summary> /// Generates a unique document name for a new node under the parent node. /// </summary> /// <param name="suggestedRoot">The suggested root to use for the unique name.</param> /// <param name="extension">The extension to use for the new file or folder (with or without the leading '.'). Can be null or empty.</param> /// <param name="isFolder">Indicates whether the new name is intended to be a file or a folder.</param> /// <returns>A unique document name for a new node under the this node.</returns> public string GenerateUniqueName(string suggestedRoot, string extension, bool isFolder) { Tracer.VerifyStringArgument(suggestedRoot, "suggestedRoot"); int suffixNumber = 0; bool foundUnique = false; string uniqueName = String.Empty; // Canonicalize the extension by setting it either to "" or prepend it with a '.' extension = ((extension == null || extension.Length == 0) ? String.Empty : PackageUtility.EnsureLeadingChar(extension, '.')); // We have to make sure that this item doesn't already exist in the hierarchy and the file system. while (!foundUnique) { if (suffixNumber == 0) { uniqueName = suggestedRoot + extension; } else { uniqueName = suggestedRoot + suffixNumber + extension; } // Look in the hierarchy to see if there is an existing item with the proposed name. foundUnique = true; foreach (Node node in this.Children) { if (PackageUtility.FileStringEquals(uniqueName, node.Caption)) { foundUnique = false; break; } } // If the name is unique within the hierarchy, we still need to check the file system. if (foundUnique) { string pathToCheck = Path.Combine(this.AbsoluteDirectory, uniqueName); if (isFolder && Directory.Exists(pathToCheck)) { foundUnique = false; } else if (!isFolder && File.Exists(pathToCheck)) { foundUnique = false; } else { // Ok, we found a unique name. break; } } // Increment the number to append to the root part of the path. suffixNumber++; } Tracer.WriteLineInformation(classType, "GenerateUniqueName", "Found a unique name for a new node. New name = '{0}'.", uniqueName); return(uniqueName); }