79756931

Date: 2025-09-05 15:03:16
Score: 2
Natty:
Report link

It is strange but the technique with the Path.GetFullPath(...) method doesn't work for me (win 10, LinqPad). For example, Path.GetFullPath("qqq") returns: "C:\Users\Lealan\AppData\Local\Temp\LINQPad8\_qkyubspn\shadow-1\qqq". And also has other issues.

So I write own IsValidPath method:

// Copyright (c) 2025 Lealan
public static bool IsValidPath(string path, in bool canExists = false)
{
    static bool isVolume(in string volume, in bool isExists)
    {
        if (volume.Length != 1 || (isExists && !Directory.Exists($"{volume}:")))
        {
            return false;
        }

        char ch = volume.First();
        return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
    }

    path = path.Trim();
    if (path.Count(Path.VolumeSeparatorChar) != 1)
    {
        return false;
    }

    int volumeIndex = path.IndexOf(Path.VolumeSeparatorChar);
    if (!isVolume(path.Substring(0, volumeIndex), canExists))
    {
        return false;
    }

    path = path.Substring(volumeIndex + 1);
    if (string.IsNullOrEmpty(path))
    {
        return true;
    }

    char dirSep = path.Count(Path.DirectorySeparatorChar) > 0
        ? path.Count(Path.AltDirectorySeparatorChar) > 0
            ? '\0'
            : Path.DirectorySeparatorChar
        : path.Count(Path.AltDirectorySeparatorChar) > 0
            ? Path.AltDirectorySeparatorChar
            : '\0';
    if (dirSep == '\0' || !path.StartsWith(dirSep) || path.Contains($"{dirSep}{dirSep}"))
    {
        return false;
    }

    path = path.Trim(dirSep);
    if (string.IsNullOrEmpty(path))
    {
        return true;
    }
        
    var invalidChars = Path.GetInvalidFileNameChars();
    return !path.Split(dirSep).Any(s => s.StartsWith(' ') || s.EndsWith(' ') || invalidChars.Any(c => s.Contains(c)));
}
Reasons:
  • RegEx Blacklisted phrase (2): doesn't work for me
  • Contains signature (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Lealan