From de45d008c72303ca4aa52e4cfe29976e22135e91 Mon Sep 17 00:00:00 2001 From: Robert McRackan Date: Tue, 7 Dec 2021 09:24:36 -0500 Subject: [PATCH] Bug fix #167 : folders with leading or trailing whitespace will break file saving. Including paths created from templates --- AppScaffolding/AppScaffolding.csproj | 2 +- FileManager/FileUtility.cs | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/AppScaffolding/AppScaffolding.csproj b/AppScaffolding/AppScaffolding.csproj index 2a5d48de..7f1a206b 100644 --- a/AppScaffolding/AppScaffolding.csproj +++ b/AppScaffolding/AppScaffolding.csproj @@ -3,7 +3,7 @@ net6.0 - 6.6.0.1 + 6.6.1.1 diff --git a/FileManager/FileUtility.cs b/FileManager/FileUtility.cs index 5ccda668..2ca30279 100644 --- a/FileManager/FileUtility.cs +++ b/FileManager/FileUtility.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.RegularExpressions; using Dinah.Core; using Polly; using Polly.Retry; @@ -65,6 +66,8 @@ namespace FileManager var fullfilename = fileStem.Truncate(MAX_FILENAME_LENGTH - extension.Length) + extension; + fullfilename = removeInvalidWhitespace(fullfilename); + var i = 0; while (File.Exists(fullfilename)) { @@ -136,6 +139,24 @@ namespace FileManager return path[0] + remainder; } + private static string removeInvalidWhitespace_pattern { get; } = $@"\s*\{Path.DirectorySeparatorChar}\s*"; + private static Regex removeInvalidWhitespace_regex { get; } = new(removeInvalidWhitespace_pattern, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace); + + /// no part of the path may begin or end in whitespace + private static string removeInvalidWhitespace(string fullfilename) + { + // no whitespace at beginning or end + // replace whitespace around path slashes + // regex (with space added for clarity) + // \s* \\ \s* => \ + fullfilename = fullfilename.Trim(); + + fullfilename = removeInvalidWhitespace_regex.Replace(fullfilename, @"\"); + + fullfilename = removeDoubleSlashes(fullfilename); + return fullfilename; + } + /// /// Move file. ///
- Ensure valid file name path: remove invalid chars, ensure uniqueness, enforce max file length