简体   繁体   中英

How to get drive root from share path?

I have a folder with some path, for example C:\\repository\\data .

I shared this folder, so it has some hostname, for example \\\\10.10.10.254\\repository\\data

I have a method

string GetDriveRootPathFromPath(IEnumerable<string> lokalPathCollection, string sharePath)
{
      var rootPath = _win32.GetVolumePathName(sharePath);
      return lokalPathCollection.FirstOrDefault(x => x.Equals(rootPath, StringComparison.OrdinalIgnoreCase));
}

they didn't work, because they cannot find disk with that name \\\\10.10.10.254\\ .

How can I modify this method to find disk C:\\ , in my example, because repository\\data are located on this disk?

Simple answer: You can't. Because a windows share doesn't contain information about the local path.

Long answer:

Since you know the IP address or hostname of the server and given that you have the permission to execute wmi queries, you could use wmi to get the information.

pulic string GetLocalPath(string computerName, string shareName)
{
    var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName));      
    scope.Connect();
    var query = new ObjectQuery("SELECT * FROM win32_share WHERE name = '" + shareName + "'");
    var searcher = new ManagementObjectSearcher(scope,query);
    var queryCollection = searcher.Get();
    foreach (ManagementObject m in queryCollection)
    {
        return m["Path"];
    }

    return null;
}

Usage:

    var path = @"\\10.10.10.254\repository\data";
    var segments = path.Split('\\');

    var computerName = segments[2];
    var shareName = segments[3];
    var localPath = GetLocalPath(computerName, shareName);
    var result = Path.Combine(localPath, String.Join("\\", segments.Skip(4)));

First of all you may share subfolder like:

c:\path1\path2\myshare

and it will look like

\\127.0.0.1\mysahre

so your example to work all shared folders should be in the root of the drive

then you can strip the leading drive from the paths in your lokalPathCollection. What I mean is instead of storing C:\\repository\\data , you will need to store repository\\data . In such case change your line to:

return "c:\\" + lokalPathCollection.FirstOrDefault(x => x.EndWith(rootPath, StringComparison.OrdinalIgnoreCase));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM