C#: Path from two base paths
Ever needed to give a user the option to enter some details and generate a path which could be a file or directory depending on what they enter, then change the path when they change their minds?
ResourceBlender uses the dialog to the right to update a filename when either of two sets of radio buttons change, or the user decides the want to output to a zip file instead of a directory.
This static method will go through each path to find a valid one. Once it’s found one, it determines whether the first path provided is a file or directory (it only uses the extension of the file, which worked for me. If you need more accurate checking you’ll need p/invoke). The file and base directory names are combined then the result returned. If the filename (the first parameter), the backup filename is used instead.
/// <summary> /// Generates a path /// The parent directory path is an array of parent directories, the first valid directory is used as the directory name. If there are no valid directories, /// My Documents is used. /// This path is combined with the fileOrDirectoryName, or if the final path is invalid, with backupFileName. /// </summary> /// <param name="fileOrDirectoryName">Name of the file or directory.</param> /// <param name="backupFileName">Filename to use incase the first filename is invalid.</param> /// <param name="paths">The paths to be used as a base for the final path, in order of preference (the first valid one will be used).</param> /// <returns>A path containing the first valid path and fileOrDirectoryName, or backupFileName if it is invalid.</returns> public static string GetPathFromBase(string fileOrDirectoryName, string backupFileName, params string[] paths) { string basePath = string.Empty; foreach(string path in paths) { if(path.Length > 0) { try { FileInfo preferredPath = new FileInfo(path); if(preferredPath.Extension.Length > 0) { // file basePath = preferredPath.Directory.FullName; } else { basePath = preferredPath.Directory.Parent.FullName; } } catch { } if(basePath.Length > 0) { // found the path break; } } } if(basePath.Length == 0) { basePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } string finalPath; try { finalPath = Combine(basePath, fileOrDirectoryName); } catch(ArgumentException) { // probably illegal characters in path finalPath = Combine(basePath, backupFileName); } return finalPath; }
I realise this is a pretty specific method and you probably won’t need to copy it exactly, but maybe it’ll give you an insight if you’re stuck.


Comments
Leave a Comment