How to programmatically discover mapped network drives on system and their server names?

前端 未结 7 1390
星月不相逢
星月不相逢 2020-11-28 06:28

I\'m trying to find out how to programmatically (I\'m using C#) determine the name (or i.p.) of servers to which my workstation has current maps. In other words, at some po

7条回答
  •  余生分开走
    2020-11-28 07:09

    I've found yet another way of doing this, which uses part of the technique sixlettervariables posted. I'd love some feedback about the pros and cons of the various techniques. For example, does mine have a downside, a scenario where it won't work, for instance?

    [DllImport("mpr.dll")]
    static extern uint WNetGetConnection(string lpLocalName, StringBuilder lpRemoteName, ref int lpnLength);
    
    internal static bool IsLocalDrive(String driveName)
    {
        bool isLocal = true;  // assume local until disproved
    
        // strip trailing backslashes from driveName
        driveName = driveName.Substring(0, 2);
    
        int length = 256; // to be on safe side 
        StringBuilder networkShare = new StringBuilder(length);
        uint status = WNetGetConnection(driveName, networkShare, ref length);
    
        // does a network share exist for this drive?
        if (networkShare.Length != 0)
        {
            // now networkShare contains a UNC path in format \\MachineName\ShareName
            // retrieve the MachineName portion
            String shareName = networkShare.ToString();
            string[] splitShares = shareName.Split('\\');
            // the 3rd array element now contains the machine name
            if (Environment.MachineName == splitShares[2])
                isLocal = true;
            else
                isLocal = false;
        }
    
        return isLocal;
    }
    

    This is called from this code:

    DriveInfo[] drives = DriveInfo.GetDrives();
    foreach (DriveInfo drive in drives)
    {
        bool isLocal = IsLocalDrive(drive.Name);
        if (isLocal)
        {
             // do whatever
        }
    }
    

提交回复
热议问题