From 50efac7bfe6ff297607034370272e0be4f6e2f8c Mon Sep 17 00:00:00 2001 From: Ben Olden-Cooligan Date: Sat, 10 Aug 2024 19:38:05 -0700 Subject: [PATCH] Fix local path to URI conversion for paths with unicode --- NAPS2.Lib/EtoForms/EtoDialogHelper.cs | 4 +-- NAPS2.Lib/Util/UriHelper.cs | 36 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 NAPS2.Lib/Util/UriHelper.cs diff --git a/NAPS2.Lib/EtoForms/EtoDialogHelper.cs b/NAPS2.Lib/EtoForms/EtoDialogHelper.cs index 5d3bb4c689..01b2108199 100644 --- a/NAPS2.Lib/EtoForms/EtoDialogHelper.cs +++ b/NAPS2.Lib/EtoForms/EtoDialogHelper.cs @@ -105,7 +105,7 @@ private void SetDir(SaveFileDialog dialog, string? defaultPath) } if (path != null) { - dialog.Directory = new Uri(Path.GetFullPath(path)); + dialog.Directory = UriHelper.FilePathToFileUri(Path.GetFullPath(path)); } } @@ -121,7 +121,7 @@ public override bool PromptToImport(out string[]? filePaths) if (Paths.IsTestAppDataPath) { // For UI test automation we choose the appdata folder to find the prepared files to import - ofd.Directory = new Uri(Path.GetFullPath(Paths.AppData)); + ofd.Directory = UriHelper.FilePathToFileUri(Path.GetFullPath(Paths.AppData)); } if (ofd.ShowDialog(null) == DialogResult.Ok) { diff --git a/NAPS2.Lib/Util/UriHelper.cs b/NAPS2.Lib/Util/UriHelper.cs new file mode 100644 index 0000000000..750090cd36 --- /dev/null +++ b/NAPS2.Lib/Util/UriHelper.cs @@ -0,0 +1,36 @@ +using System.Text; + +namespace NAPS2.Util; + +public class UriHelper +{ + // From https://stackoverflow.com/a/35734486/2112909 + public static string FilePathToFileUrl(string filePath) + { + StringBuilder uri = new StringBuilder(); + foreach (char v in filePath) + { + if ((v >= 'a' && v <= 'z') || (v >= 'A' && v <= 'Z') || (v >= '0' && v <= '9') || + v == '+' || v == '/' || v == ':' || v == '.' || v == '-' || v == '_' || v == '~' || + v > '\xFF') + { + uri.Append(v); + } + else if (v == Path.DirectorySeparatorChar || v == Path.AltDirectorySeparatorChar) + { + uri.Append('/'); + } + else + { + uri.Append(String.Format("%{0:X2}", (int)v)); + } + } + if (uri.Length >= 2 && uri[0] == '/' && uri[1] == '/') // UNC path + uri.Insert(0, "file:"); + else + uri.Insert(0, "file:///"); + return uri.ToString(); + } + + public static Uri FilePathToFileUri(string filePath) => new(FilePathToFileUrl(filePath)); +} \ No newline at end of file