xoofx / zio

A cross-platform abstract/virtual filesystem framework with many built-ins filesystems for .NET
BSD 2-Clause "Simplified" License
806 stars 61 forks source link

MountFileSystem getting the physical path #82

Open Ellested opened 4 months ago

Ellested commented 4 months ago

I was trying to get the pysical path of a file within a mounted file system, but it's not super happy about it, I assumed the ConvertPathToInternal would return this, but it returns the input path. I then checked the code and noticed it didn't use the mounts at all.

So I cooked this little extension up - maybe someone can improve and add it to a future release.

public static class ZioExtensions
{
    public static string GetPhysicalPath(this IFileSystem fs, UPath path)
    {
        if (fs is MemoryFileSystem) throw new Exception($"Path '{path}' does not have a physical path on MemoryFileSystems");
        if (fs is MountFileSystem mfs) return GetPhysicalPath(mfs, path);
        return fs.ConvertPathToInternal(path);
    }

    public static string GetPhysicalPath(this MountFileSystem mfs, UPath path) {
        if (mfs.TryGetMount(path, out var name, out var fs, out var fsPath)) {
            return fs?.GetPhysicalPath(fsPath ?? throw new Exception($"Path '{path}' does not have a physical path - internal error"));
        }
        try
        {
            return mfs.ConvertPathToInternal(path);
        }
        catch (InvalidOperationException)
        {
            throw new Exception($"Path '{path}' does not have a physical path on this MountFileSystem and no delegate fallback was provided");
        }
    }
}

PS. Sorry for not submitting a PR with tests and everything, I have too much going at the moment...