예제 #1
0
        public static string ReplaceInvalidPathChars(string path, CharReplacementEvaluatorDelegate replacementEvaluator, InvalidPathCharsOptions options = InvalidPathCharsOptions.Default)
        {
            string             rootPath          = string.Empty;
            IEnumerable <char> invalidCharacters = Enumerable.Empty <char>();

            if (options.HasFlag(InvalidPathCharsOptions.ReplaceInvalidPathChars))
            {
                invalidCharacters = invalidCharacters.Concat(System.IO.Path.GetInvalidPathChars());
            }

            if (options.HasFlag(InvalidPathCharsOptions.ReplaceInvalidFileNameChars))
            {
                invalidCharacters = invalidCharacters.Concat(System.IO.Path.GetInvalidFileNameChars());
            }

            if (options.HasFlag(InvalidPathCharsOptions.PreserveDirectoryStructure))
            {
                // The root of the path might contain characters that would be invalid file name characters (e.g. ':' in "C:\").
                // In order to preserve the root path information, we'll remove it for now and add it back later.

                rootPath = System.IO.Path.GetPathRoot(ReplaceInvalidPathChars(path, InvalidPathCharsOptions.ReplaceInvalidPathChars));

                path = path.Substring(rootPath.Length);

                invalidCharacters = invalidCharacters.Where(c => c != System.IO.Path.DirectorySeparatorChar && c != System.IO.Path.AltDirectorySeparatorChar);
            }

            HashSet <char> invalidCharacterLookup = new HashSet <char>(invalidCharacters);
            StringBuilder  pathBuilder            = new StringBuilder();

            foreach (char c in path.ToCharArray())
            {
                if (invalidCharacterLookup.Contains(c))
                {
                    pathBuilder.Append(replacementEvaluator(c));
                }
                else
                {
                    pathBuilder.Append(c);
                }
            }

            path = pathBuilder.ToString();

            if (!string.IsNullOrEmpty(rootPath))
            {
                path = System.IO.Path.Combine(rootPath, path);
            }

            return(path);
        }
예제 #2
0
 public static string ReplaceInvalidPathChars(string path, string replacement, InvalidPathCharsOptions options = InvalidPathCharsOptions.Default)
 {
     return(ReplaceInvalidPathChars(path, _ => replacement, options));
 }
예제 #3
0
 public static string ReplaceInvalidPathChars(string path, ICharReplacementEvaluator replacementEvaluator, InvalidPathCharsOptions options = InvalidPathCharsOptions.Default)
 {
     return(ReplaceInvalidPathChars(path, replacementEvaluator.Replace, options));
 }
예제 #4
0
 public static string ReplaceInvalidPathChars(string path, InvalidPathCharsOptions options = InvalidPathCharsOptions.Default)
 {
     return(ReplaceInvalidPathChars(path, "_", options));
 }