Skip to content

Commit

Permalink
Fix local path to URI conversion for paths with unicode
Browse files Browse the repository at this point in the history
  • Loading branch information
cyanfish committed Aug 11, 2024
1 parent cbebedf commit 50efac7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
4 changes: 2 additions & 2 deletions NAPS2.Lib/EtoForms/EtoDialogHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

Expand All @@ -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)
{
Expand Down
36 changes: 36 additions & 0 deletions NAPS2.Lib/Util/UriHelper.cs
Original file line number Diff line number Diff line change
@@ -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));
}

0 comments on commit 50efac7

Please sign in to comment.