Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

后端 未结 10 1030
走了就别回头了
走了就别回头了 2020-11-22 05:12

We\'ve run into an interesting situation that needs solving, and my searches have turned up nill. I therefore appeal to the SO community for help.

The issue is this:

10条回答
  •  抹茶落季
    2020-11-22 05:39

    Here a minimal POC class w/ all the cruft removed

    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    
    public class UncShareWithCredentials : IDisposable
    {
        private string _uncShare;
    
        public UncShareWithCredentials(string uncShare, string userName, string password)
        {
            var nr = new Native.NETRESOURCE
            {
                dwType = Native.RESOURCETYPE_DISK,
                lpRemoteName = uncShare
            };
    
            int result = Native.WNetUseConnection(IntPtr.Zero, nr, password, userName, 0, null, null, null);
            if (result != Native.NO_ERROR)
            {
                throw new Win32Exception(result);
            }
            _uncShare = uncShare;
        }
    
        public void Dispose()
        {
            if (!string.IsNullOrEmpty(_uncShare))
            {
                Native.WNetCancelConnection2(_uncShare, Native.CONNECT_UPDATE_PROFILE, false);
                _uncShare = null;
            }
        }
    
        private class Native
        {
            public const int RESOURCETYPE_DISK = 0x00000001;
            public const int CONNECT_UPDATE_PROFILE = 0x00000001;
            public const int NO_ERROR = 0;
    
            [DllImport("mpr.dll")]
            public static extern int WNetUseConnection(IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID,
                int dwFlags, string lpAccessName, string lpBufferSize, string lpResult);
    
            [DllImport("mpr.dll")]
            public static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);
    
            [StructLayout(LayoutKind.Sequential)]
            public class NETRESOURCE
            {
                public int dwScope;
                public int dwType;
                public int dwDisplayType;
                public int dwUsage;
                public string lpLocalName;
                public string lpRemoteName;
                public string lpComment;
                public string lpProvider;
            }
        }
    }
    

    You can directly use \\server\share\folder w/ WNetUseConnection, no need to strip it to \\server part only beforehand.

提交回复
热议问题