From 8b1281862de1464db3be7500505f7c2f2f59259a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 15 Sep 2024 15:40:28 -0500 Subject: assume remote filenames use a backslash, unless forward slashes are present --- src/slskd/Common/CommonExtensions.cs | 37 +++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index a68ce2f2..44e3c034 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -132,6 +132,39 @@ namespace slskd return differences; } + /// + /// Makes a best-guess determination of the directory separator character used by a remote system, + /// based on the characters present in the specified . + /// + /// The fully qualified remote filename to inspect. + /// The guessed directory separator. + public static char GuessDirectorySeparator(this string remoteFilename) + { + // forward slash is a forbidden character on all operating systems; if the specified string contains it, + // then it is coming from the OS's directory separator + if (remoteFilename.Contains('/')) + { + return '/'; + } + + // if the given string doesn't contain any forward slashes, it either lacks a directory separator at all + // (potentially impossible?) or it is using backspaces. backspaces are used by all major clients, so + // this should be a safe assumption. + return '\\'; + } + + /// + /// Returns the directory name of the given , using the specified + /// to split and join directories and filename. + /// + /// The path for which to return the directory name. + /// The directory separator character. + /// The specified path, less the last segment. + public static string GetDirectoryName(this string path, char directorySeparator) + { + return string.Join(directorySeparator, path.Split(directorySeparator).SkipLast(1)); + } + /// /// Returns the directory from the given path, regardless of separator format. /// @@ -139,9 +172,7 @@ namespace slskd /// The directory. public static string DirectoryName(this string path) { - var separator = path.Contains('\\') ? '\\' : '/'; - var parts = path.Split(separator); - return string.Join(separator, parts.Take(parts.Length - 1)); + return path.GetDirectoryName(path.GuessDirectorySeparator()); } /// -- cgit v1.2.3