Fix local path to URI conversion for paths with unicode

This commit is contained in:
Ben Olden-Cooligan 2024-08-10 19:38:05 -07:00
parent cbebedf2a9
commit 50efac7bfe
2 changed files with 38 additions and 2 deletions

View File

@ -105,7 +105,7 @@ public class EtoDialogHelper : DialogHelper
}
if (path != null)
{
dialog.Directory = new Uri(Path.GetFullPath(path));
dialog.Directory = UriHelper.FilePathToFileUri(Path.GetFullPath(path));
}
}
@ -121,7 +121,7 @@ public class EtoDialogHelper : DialogHelper
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)
{

View File

@ -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));
}