在Windows 10上以C#编程方式映射网络驱动器

时间:2017-04-02 21:56:15

标签: c# network-programming

我按照以下链接以编程方式映射网络驱动器: Mapping Network Drive using C#

驱动器似乎连接正确,因为我可以查询C#中的目录和文件。但我在电脑上看不到驱动器。 我的目标是以编程方式为我的用户映射某些驱动器。 我不想使用batch / cmd ... Windows 10可能存在问题,或者此代码是否适合编程方法。

亲切的问候

使用代码:

Utility.NetworkDrive.MapNetworkDrive("R", @"\\unc\path");
var dirs = Directory.GetDirectories("R:"); // got many nice directories...
Utility.NetworkDrive.DisconnectNetworkDrive("R", true);

完整代码:

namespace Utility
{
    public class NetworkDrive
    {
        private enum ResourceScope
        {
            RESOURCE_CONNECTED = 1,
            RESOURCE_GLOBALNET,
            RESOURCE_REMEMBERED,
            RESOURCE_RECENT,
            RESOURCE_CONTEXT
        }
        private enum ResourceType
        {
            RESOURCETYPE_ANY,
            RESOURCETYPE_DISK,
            RESOURCETYPE_PRINT,
            RESOURCETYPE_RESERVED
        }
        private enum ResourceUsage
        {
            RESOURCEUSAGE_CONNECTABLE = 0x00000001,
            RESOURCEUSAGE_CONTAINER = 0x00000002,
            RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
            RESOURCEUSAGE_SIBLING = 0x00000008,
            RESOURCEUSAGE_ATTACHED = 0x00000010
        }
        private enum ResourceDisplayType
        {
            RESOURCEDISPLAYTYPE_GENERIC,
            RESOURCEDISPLAYTYPE_DOMAIN,
            RESOURCEDISPLAYTYPE_SERVER,
            RESOURCEDISPLAYTYPE_SHARE,
            RESOURCEDISPLAYTYPE_FILE,
            RESOURCEDISPLAYTYPE_GROUP,
            RESOURCEDISPLAYTYPE_NETWORK,
            RESOURCEDISPLAYTYPE_ROOT,
            RESOURCEDISPLAYTYPE_SHAREADMIN,
            RESOURCEDISPLAYTYPE_DIRECTORY,
            RESOURCEDISPLAYTYPE_TREE,
            RESOURCEDISPLAYTYPE_NDSCONTAINER
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct NETRESOURCE
        {
            public ResourceScope oResourceScope;
            public ResourceType oResourceType;
            public ResourceDisplayType oDisplayType;
            public ResourceUsage oResourceUsage;
            public string sLocalName;
            public string sRemoteName;
            public string sComments;
            public string sProvider;
        }
        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2
            (ref NETRESOURCE oNetworkResource, string sPassword,
            string sUserName, int iFlags);

        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2
            (string sLocalName, uint iFlags, int iForce);

        public static void MapNetworkDrive(string sDriveLetter, string sNetworkPath)
        {
            //Checks if the last character is \ as this causes error on mapping a drive.
            if (sNetworkPath.Substring(sNetworkPath.Length - 1, 1) == @"\")
            {
                sNetworkPath = sNetworkPath.Substring(0, sNetworkPath.Length - 1);
            }

            NETRESOURCE oNetworkResource = new NETRESOURCE()
            {
                oResourceType = ResourceType.RESOURCETYPE_DISK,
                sLocalName = sDriveLetter + ":",
                sRemoteName = sNetworkPath
            };

            //If Drive is already mapped disconnect the current 
            //mapping before adding the new mapping
            if (IsDriveMapped(sDriveLetter))
            {
                DisconnectNetworkDrive(sDriveLetter, true);
            }

            WNetAddConnection2(ref oNetworkResource, null, null, 0);
        }

        public static int DisconnectNetworkDrive(string sDriveLetter, bool bForceDisconnect)
        {
            if (bForceDisconnect)
            {
                return WNetCancelConnection2(sDriveLetter + ":", 0, 1);
            }
            else
            {
                return WNetCancelConnection2(sDriveLetter + ":", 0, 0);
            }
        }

        public static bool IsDriveMapped(string sDriveLetter)
        {
            string[] DriveList = Environment.GetLogicalDrives();
            for (int i = 0; i < DriveList.Length; i++)
            {
                if (sDriveLetter + ":\\" == DriveList[i].ToString())
                {
                    return true;
                }
            }
            return false;
        }

    }

}

3 个答案:

答案 0 :(得分:4)

休息我的笔记本电脑似乎解决了窗户的每个问题。 以下所有三种方法都像魅力一样。我最喜欢的一个当然是C#“唯一”的方法。

        // Approach 1
        Utility.NetworkDrive.MapNetworkDrive("R", @"\\unc\path");
        var dirs1 = Directory.GetDirectories("R:");
        Utility.NetworkDrive.DisconnectNetworkDrive("R", true);

        // Approach 2
        DoProcess("net", @"use R: \\unc\path");
        var dirs2 = Directory.GetDirectories("R:");
        DoProcess("net", "use /D R:");

        // Approach 3
        DoProcess("cmd", @"/c C:\local\path\to\batch\connect.cmd");
        var dirs3 = Directory.GetDirectories("R:");
        DoProcess("cmd", @"/c C:\local\path\to\batch\diconnect.cmd");

    public static string DoProcess(string cmd, string argv)
    {

        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = cmd;
        p.StartInfo.Arguments = $" {argv}";
        p.StartInfo.CreateNoWindow = true;
        p.Start();
        p.WaitForExit();
        string output = p.StandardOutput.ReadToEnd();
        p.Dispose();

        return output;

    }

答案 1 :(得分:0)

如果您使用@Mario的方法2并希望保留驱动器,请删除以下行:

DoProcess("net", "use /D R:");

答案 2 :(得分:0)

映射的驱动器可能会非常混乱。问题是它们仅对创建它们的“用户”出现。关于UAC和以管理员身份运行的评论中的问题暗示了这一点。

如果您“以其他人的身份运行”,则驱动器将只为该人显示。

如果您仅担心用户与高级用户访问,则可以使用注册表项来启用此功能: HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Policies \ System

EnableLinkedConnections

请参阅此以获取更多详细信息: https://docs.microsoft.com/en-us/troubleshoot/windows-client/networking/mapped-drives-not-available-from-elevated-command