예제 #1
0
        private void bnLogin_Click(object sender, EventArgs e)
        {
            NETRESOURCE netResource = new NETRESOURCE();
            netResource.dwScope = 0;
            netResource.dwType = 0;
            netResource.dwDisplayType = 0;
            netResource.LocalName = "h:";
            netResource.RemoteName = @"\\$SERVER-IP\users\home\" + username.Text;
            netResource.dwUsage = 0;
            netResource.Comment = "";
            netResource.Provider = "";

            // Try the H: Drive - domain1
            int hReturnValue = WNetAddConnection2(netResource, password.Text, "$DOMAIN1\\" + username.Text, 0);

            // Try the S: Drive - domain1
            netResource.LocalName = "s:";
            netResource.RemoteName = @"\\$SERVER-IP\share";
            int sReturnValue = WNetAddConnection2(netResource, password.Text, "$DOMAIN1\\" + username.Text, 0);

            // If domain1 fails, the user may still
            // be on domain2, so try the username
            // with domain2
            if (hReturnValue > 0 || sReturnValue > 0)
            {
                // Try the H: Drive - domain2
                netResource.LocalName = "h:";
                netResource.RemoteName = @"\\$SERVER-IP\users\home\" + username.Text;
                hReturnValue = WNetAddConnection2(netResource, password.Text, "$DOMAIN2\\" + username.Text, 0);

                // Try the S: Drive - domain2
                netResource.LocalName = "s:";
                netResource.RemoteName = @"\\SERVER-IP\share";
                sReturnValue = WNetAddConnection2(netResource, password.Text, "$DOMAIN2\\" + username.Text, 0);
            }

            // Check the return value from WNetAddConnection2
            if (hReturnValue == 0) // Sucessful Connection
            {
                // Hide Form1
                this.Hide();

                // Create a new instance of the sleeper class
                sleeper sleeperForm = new sleeper();

                // Show the sleeper form
                if (sleeperForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    WNetCancelConnection2("h:", 0, 1);
                    WNetCancelConnection2("s:", 0, 1);
                    this.Close();
                }
            }
            else // Failed Connection
            {
                // TODO -- Add statements to differentiate error numbers
                // the current method isn't all too helpful
                MessageBox.Show("Invalid username or password, please try again.\nError Code: " + hReturnValue,"Login Attempt Failed");
            }
        }
예제 #2
0
        public bool TryConnect(string serverName)
        {
            Server server;
            if (!_serverProvider.TryGetServer(serverName, out server))
            {
                return false;
            }

            if (_serverCache.ContainsKey(server.Name))
            {
                return true;
            }

            var remoteName = GetRemoteName(serverName);
            var n = new NETRESOURCE
                {
                    dwScope = 0,
                    dwType = RESOURCETYPE_ANY,
                    dwDisplayType = 0,
                    dwUsage = 0,
                    lpLocalName = null,
                    lpRemoteName = remoteName,
                    lpComment = null,
                    lpProvider = null
                };

            var returnCode = WNetAddConnection2(ref n, server.Password, server.User, 0);
            if (returnCode == 1219 || returnCode <= 0)
            {
                _serverCache.TryAdd(server.Name, server);
                return true;
            }
            throw new Win32Exception(returnCode);
        }
예제 #3
0
 private static extern int WNetUseConnection(
     IntPtr hwndOwner,
     NETRESOURCE lpNetResource,
     string lpPassword,
     string lpUserID,
     int dwFlags,
     string lpAccessName,
     string lpBufferSize,
     string lpResult
     );
예제 #4
0
파일: FilePath.cs 프로젝트: avs009/gsf
        /// <summary>Connects to a network share with the specified user's credentials.</summary>
        /// <param name="sharename">UNC share name to connect to.</param>
        /// <param name="username">Username to use for connection.</param>
        /// <param name="password">Password to use for connection.</param>
        /// <param name="domain">Domain name to use for connetion. Specify the computer name for local system accounts.</param>
        public static void ConnectToNetworkShare(string sharename, string username, string password, string domain)
        {
            NETRESOURCE resource = new NETRESOURCE();
            int result;

            resource.dwType = RESOURCETYPE_DISK;
            resource.lpRemoteName = sharename;

            if (domain.Length > 0)
                username = domain + "\\" + username;

            result = WNetAddConnection2(ref resource, password, username, 0);
            if (result != 0)
                throw new InvalidOperationException("Failed to connect to network share \"" + sharename + "\" as user " + username + ". " + WindowsApi.GetErrorMessage(result));
        }
예제 #5
0
 public static int MapDrive(string driveletter, string unc)
 {
     NETRESOURCE ConnInf = new NETRESOURCE();
     ConnInf.dwScope = 0;
     ConnInf.dwType = RESOURCETYPE_ANY;
     ConnInf.dwDisplayType = 0;
     ConnInf.dwUsage = 0;
     ConnInf.lpLocalName = driveletter;
     ConnInf.lpRemoteName = unc;
     ConnInf.lpComment = null;
     ConnInf.lpProvider = null;
     int ret = WNetAddConnection2(ref ConnInf, null, null,0);
     if (ret != 0)
         throw new IOException("An error occured mapping the resource.  The error code is: " + ret);
     return ret;
 }
예제 #6
0
		/// <summary>
		/// Maps the network resouce to the specified share name
		/// </summary>
		/// <param name="hwnd">Owner window handle</param>
		/// <param name="netRes">Network resource to connect</param>
		/// <param name="shareName">Share name</param>
		/// <param name="userName">User name</param>
		/// <param name="password">Password</param>
		public static void MapDrive(IntPtr hwnd, string netRes, string shareName, string userName, string password)
		{
			NETRESOURCE NetRes = new NETRESOURCE();			
			NetRes.dwScope = RESOURCE_GLOBALNET | RESOURCE_REMEMBERED;
			NetRes.dwType = RESOURCETYPE_DISK;
			NetRes.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
			NetRes.dwUsage = RESOURCEUSAGE_CONNECTABLE;
			NetRes.lpRemoteName = MarshalEx.StringToHGlobalUni(netRes);
			NetRes.lpLocalName = MarshalEx.StringToHGlobalUni(shareName);
			NetRes.lpComment = IntPtr.Zero;
			NetRes.lpProvider = IntPtr.Zero;
				
			int ret = WNetAddConnection3(hwnd, NetRes, password, userName, 1);

			if (ret != 0)
			{
				throw new System.ComponentModel.Win32Exception(ret, ((NetworkErrors)ret).ToString());
			}
				
		}
예제 #7
0
        /// <summary>
        /// 공유 폴더에 대한 네트워크 연결을 만든다.
        /// </summary>
        /// <param name="remoteAccessUri">원격 공유폴더 경로</param>
        /// <param name="remoteUserId">원격 사용자 아이디</param>
        /// <param name="remotePassword">원격 비밀번호</param>
        /// <param name="localDriveName">사용가능한 드라이브 명, NULL일때 시스템이 자동으로 설정한다.</param>
        public static void Connect(string remoteAccessUri, string remoteUserId, string remotePassword, string localDriveName)
        {
            if(IsDebugEnabled)
                log.Debug("네트웍 드라이브를 만든다. remoteAccessUri=[{0}], remoteUserId=[{1}], remotePassword=[{2}], localDriveName=[{3}]",
                          remoteAccessUri, remoteUserId, remotePassword, localDriveName);

            var capacity = 64;
            uint resultFlags;
            const uint flags = 0;

            var lpAccessName = new StringBuilder(capacity);

            var netResource = new NETRESOURCE
                              {
                                  dwType = 1,
                                  lpLocalName = localDriveName,
                                  lpRemoteName = remoteAccessUri,
                                  lpProvider = null
                              };

            // 공유 디스크
            // 로컬 드라이브 지정하지 않음
            var result = WNetUseConnection(IntPtr.Zero,
                                           ref netResource,
                                           remotePassword,
                                           remoteUserId,
                                           flags,
                                           lpAccessName,
                                           ref capacity,
                                           out resultFlags);

            if(IsDebugEnabled)
                log.Debug("네트웍 드라이브 빌드. result=[{0}], lpAccessname=[{1}]", result, lpAccessName.ToString());

            if(result != 0)
                throw new Win32Exception(result);
        }
예제 #8
0
 private static extern ErrorCodes WNetOpenEnum(ResourceScope dwScope, ResourceType dwType, ResourceUsage dwUsage,
                                               NETRESOURCE p, out IntPtr lphEnum);
 private static extern int WNetAddConnection2(NETRESOURCE lpNetResource,
                                              string lpPassword,
                                              string lpUsername,
                                              System.UInt32 dwFlags);
예제 #10
0
파일: FilePath.cs 프로젝트: avs009/gsf
 private static extern int WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string lpUsername, int dwFlags);
 private static extern int WNetAddConnection2
     (ref NETRESOURCE oNetworkResource, string sPassword,
     string sUserName, int iFlags);
 private static extern int WNetAddConnection2(ref NETRESOURCE oNetworkResource, string sPassword,
     string sUserName, int iFlags);
예제 #13
0
            private static void ConnectToRemote(string remoteUNC, string username, string password, bool promptUser, bool multipleCredentialsInProgress)
            {
                NETRESOURCE nr = new NETRESOURCE();
                nr.dwType = RESOURCETYPE_DISK;
                nr.lpRemoteName = Clean(remoteUNC);
                //			nr.lpLocalName = "F:";

                int ret;
                if (promptUser)
                    ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
                else
                    ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

                if (ret == NO_ERROR) return;
                if (ret == ERROR_MULTIPLE_CREDENTIALS && !multipleCredentialsInProgress)
                {
                    DisconnectRemote(remoteUNC);
                    ConnectToRemote(remoteUNC, username, password, promptUser, true);
                    return;
                }
                throw new InvalidOperationException(GetErrorForNumber(ret));
            }
예제 #14
0
            /// <summary>
            /// Connect to the share
            /// </summary>
            public static void Connect(string remoteShare, string username, string password)
            {
                _remoteShare = remoteShare.Split('\\')[2];
                _remoteShare = @"\\" + _remoteShare;

                NETRESOURCE netRes = new NETRESOURCE
                {
                    dwType = RESOURCETYPE_DISK,
                    lpRemoteName = _remoteShare
                };

                int result = WNetUseConnection(IntPtr.Zero, netRes, password, username, 0, null, null, null);

                if (result != 0)
                {
                    throw new Win32Exception(result);
                }
            }
예제 #15
0
 private static extern int WNetAddConnection3(
     IntPtr hwndOwner,
     NETRESOURCE lpNetResource,
     string lpPassword,
     string lpUserName,
     int dwFlags);
예제 #16
0
 private static extern int WNetAddConnection2(
     NETRESOURCE netResource,
     [MarshalAs(UnmanagedType.LPWStr)] string sPassword,
     [MarshalAs(UnmanagedType.LPWStr)] string sUsername,
     uint dwFlags
     );
예제 #17
0
#pragma warning restore 414
#endif

        #endregion

        #region Static Interface
        public static bool CreateNullSession(string sServer, string sShortname, CredentialEntry ce)
        {
            Logger.Log(
                String.Format("Session.CreateNullSession({0}, {1}, {2}) called", sServer, sShortname, ce),
                Logger.netAPILogLevel);

            int nErr;

            // set up the user name and password; map "root" as needed
            string sUsername;
            string sPassword;

            if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
            {
                if (ce != null && !ce.DefaultCreds && ce.Password != new String('*', 16))
                {
                    if (ce.UserName.IndexOf('\\') < 0 && !String.IsNullOrEmpty(ce.Domain))
                    {
                        sUsername = String.Format("{0}\\{1}", ce.Domain, ce.UserName);
                    }
                    else
                    {
                        sUsername = ce.UserName;
                    }
                    sPassword = ce.Password;
                }
                else
                {
                    // setup for default creds
                    sUsername = null;
                    sPassword = null;
                    Logger.Log("CreateNullSession(): Using default creds", Logger.netAPILogLevel);
                }
            }
            else
            {
                if (ce.UserName.IndexOf(@"\") < 0 && !String.IsNullOrEmpty(ce.Domain))
                {
                    sUsername = String.Format("{0}\\{1}", ce.Domain, ce.UserName);
                }
                else
                {
                    sUsername = ce.UserName;
                }
                sPassword = ce.Password;
            }

            // set up a NETRESOURCE structure
            NETRESOURCE nr = new NETRESOURCE();

            nr.dwScope       = 0;
            nr.dwType        = 0;
            nr.dwDisplayType = 0;
            nr.dwUsage       = 0;
            nr.LocalName     = null;
            nr.RemoteName    = @"\\" + sServer + @"\IPC$";
            nr.Comment       = null;
            nr.Provider      = null;

            // try the operation. Throws exception if it fails.
            if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
            {
                nErr = WindowsSession.WNetAddConnection2(nr, sPassword, sUsername, 0);
            }
            else
            {
                nErr = WNetAddConnection2(nr, sPassword, sUsername, 0);
            }

            //HACK: WNetAddConnection2 appears to return 'access denied' even when it has just granted access!
            //this is a workaround with the side-effect that the user will never be warned when their password
            //is invalid.
            if (nErr == (int)ErrorCodes.WIN32Enum.ERROR_ACCESS_DENIED)
            {
                Logger.Log(String.Format("CreateNullSession(): Ignoring error!  nErr={0}: {1}",
                                         nErr, ErrorCodes.WIN32String(nErr)), Logger.LogLevel.Error);

                System.Windows.Forms.MessageBox.Show("WNetAddConnection2 success but ERROR_ACCESS_DENIED");

                return(true);
            }
            else if (nErr != 0)
            {
                ce.Invalidate(sServer);

                Logger.Log(String.Format("CreateNullSession(): nErr={0}: {1}",
                                         nErr, ErrorCodes.WIN32String(nErr)), Logger.LogLevel.Error);
                return(false);
            }

            Logger.Log("CreateNullSession() successful", Logger.netAPILogLevel);

            return(true);
        }
예제 #18
0
        public ServerEnum(ResourceScope scope, ResourceType type, ResourceUsage usage, ResourceDisplayType displayType)
        {
            NETRESOURCE pRsrc = new NETRESOURCE();

            EnumerateServers(pRsrc, scope, type, usage, displayType);
        }
        /// <summary>
        ///     Establishes a connection to a Windows network resource.
        /// </summary>
        /// <param name="resource"> The path of the resource (e.g. a UNC path to a file share). </param>
        /// <param name="username"> The logon name under which the connection is to be established (null for the current user). </param>
        /// <param name="password"> The password for the logon if <paramref name="username" /> is specified. </param>
        /// <param name="interactive">
        ///     Specifies whether an interactive logon can be performed if necessary (e.g. the user might be
        ///     asked to enter credentials).
        /// </param>
        /// <returns>
        ///     The error which occurred during establishing the network connection.
        ///     <see cref="WindowsNetworkError.None" /> is returned if the connection was established successfully.
        /// </returns>
        /// <remarks>
        ///     <note type="important">
        ///         Whether and how the connection is established depends heavily on the configuration of Windows, the computer,
        ///         the network, and the remote resource itself.
        ///         This is even more true for using interactive logon (<paramref name="interactive" />).
        ///     </note>
        /// </remarks>
        /// <exception cref="ArgumentNullException"> <paramref name="resource" /> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="resource" /> is an empty string. </exception>
        /// <exception cref="Win32Exception">
        ///     An unknown error occurred which could not be translated to
        ///     <see cref="WindowsNetworkError" />.
        /// </exception>
        public static WindowsNetworkError OpenConnection(string resource, string username, string password,
                                                         bool interactive)
        {
            if (resource == null)
            {
                throw new ArgumentNullException(nameof(resource));
            }

            if (string.IsNullOrWhiteSpace(resource))
            {
                throw new ArgumentException("The string is empty", nameof(resource));
            }

            NETRESOURCE connection = new NETRESOURCE();

            connection.dwType     = WindowsNetwork.ResourcetypeAny;
            connection.LocalName  = null;
            connection.RemoteName = resource;
            connection.Provider   = null;

            int errorCode = WindowsNetwork.WNetAddConnection3(IntPtr.Zero, ref connection, password, username,
                                                              interactive ? (WindowsNetwork.ConnectInteractive |
                                                                             WindowsNetwork.ConnectPrompt) : 0);

            WindowsNetworkError error;

            switch (errorCode)
            {
            default:
            {
                string errorMessage = WindowsApi.GetErrorMessage(errorCode);
                throw new Win32Exception(errorCode, errorMessage);
            }

            case (int)WindowsError.ErrorSuccess:
            {
                error = WindowsNetworkError.None;
                break;
            }

            case (int)WindowsError.ErrorBadNetName:
            {
                error = WindowsNetworkError.InvalidParameters;
                break;
            }

            case (int)WindowsError.ErrorInvalidPassword:
            {
                error = WindowsNetworkError.InvalidPassword;
                break;
            }

            case (int)WindowsError.ErrorCancelled:
            {
                error = WindowsNetworkError.CanceledByUser;
                break;
            }

            case (int)WindowsError.ErrorBusy:
            {
                error = WindowsNetworkError.Busy;
                break;
            }

            case (int)WindowsError.ErrorNoNetOrBadPath:
            {
                error = WindowsNetworkError.Unavailable;
                break;
            }

            case (int)WindowsError.ErrorNoNetwork:
            {
                error = WindowsNetworkError.Unavailable;
                break;
            }
            }

            return(error);
        }
 private static extern int WNetAddConnection3(IntPtr hWndOwner, ref NETRESOURCE lpNetResource,
                                              [MarshalAs(UnmanagedType.LPWStr)] string lpPassword,
                                              [MarshalAs(UnmanagedType.LPWStr)] string lpUserName, int dwFlags);
예제 #21
0
 public ServerEnum(ResourceScope scope, ResourceType type, ResourceUsage usage, ResourceDisplayType displayType,string kPath)
 {
     NETRESOURCE netRoot = new NETRESOURCE();
     EnumerateServers(netRoot, scope, type, usage, displayType,kPath);
 }
예제 #22
0
        public static IEnumerable <string> GetAllAvailableNetworkDevices()
        {
            NETRESOURCE pRsrc = new NETRESOURCE();

            return(EnumerateServers(pRsrc, ResourceScope.RESOURCE_GLOBALNET, ResourceType.RESOURCETYPE_DISK, ResourceUsage.RESOURCEUSAGE_ALL, ResourceDisplayType.RESOURCEDISPLAYTYPE_SERVER));
        }
        /// <summary>
        /// Map the network resource.
        /// </summary>
        public void MapNetworkDrive()
        {
            if (_mapped)
            {
                UnMapNetworkDrive();
            }

            NETRESOURCE netResource = new NETRESOURCE();
            netResource.dwScope = 2;
            netResource.dwType = RESOURCETYPE_DISK;
            netResource.dwDisplayType = 3;
            netResource.dwUsage = 1;
            netResource.lpRemoteName = GuestPathToNetworkPath(_info.RemotePath);
            netResource.lpLocalName = _info.LocalPath;
            int rc = WNetAddConnection2(ref netResource, _info.Password, _info.Username, 0);
            if (rc != 0)
            {
                throw new Win32Exception(rc);
            }

            _networkPath = netResource.lpRemoteName;
            _mapped = true;
        }
 private static extern int WNetUseConnection(IntPtr howner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID,
                                             int dwFlags, string lpAccessName, string lpBufferSize, string lpResult);
예제 #25
0
파일: pInvokes.cs 프로젝트: leoayt/pgina
 public static extern int WNetAddConnection2(NETRESOURCE netResource,
                                             string password, string username, int flags);
예제 #26
0
파일: Mapeo.cs 프로젝트: jcrajat/DAL_Design
        public EnumNET_ERROR Conectar()
        {
            var NetR = new NETRESOURCE();

            NetR.dwScope = (int)EnumNET_RESOURCE.RESOURCE_GLOBALNET;
            NetR.dwType = (int)EnumNET_RESOURCE.RESOURCETYPE_DISK;
            NetR.dwDisplayType = (int)EnumNET_RESOURCE.RESOURCEDISPLAYTYPE_SHARE;
            NetR.dwUsage = (int)EnumNET_RESOURCE.RESOURCEUSAGE_CONNECTABLE;
            NetR.lpLocalName = Unidad; // If undefined, Connect with no device
            NetR.lpRemoteName = Carpeta; // Your valid share
            //NetR.lpComment = "Optional Comment"
            //NetR.lpProvider =    ' Leave this undefined

            // If the UserName and Password arguments are NULL, the user context
            // for the process provides the default user name.
            return (EnumNET_ERROR)WNetAddConnection2(ref NetR, Contraseña, Usuario, (int)EnumNET_RESOURCE.CONNECT_UPDATE_PROFILE);
        }
예제 #27
0
        private List<NETRESOURCE> GetNetworkConnections(
            )
        {
            NETRESOURCE NetResource = new NETRESOURCE();

            NetResource.dwScope = ResourceScope.RESOURCE_CONNECTED;
            NetResource.dwUsage = ResourceUsage.RESOURCEUSAGE_ALL;
            NetResource.dwType = ResourceType.RESOURCETYPE_DISK;

            return GetChildNetResources(ResourceScope.RESOURCE_CONNECTED,
                                        ResourceType.RESOURCETYPE_DISK,
                                        ResourceUsage.RESOURCEUSAGE_ALL,
                                        NetResource);
        }
예제 #28
0
 private static extern int WNetAddConnection2(
     ref NETRESOURCE lpNetResource, string lpPassword, string UserName, int dwFlags);
예제 #29
0
        private static IEnumerable<string> EnumerateServers(NETRESOURCE pRsrc, ResourceScope scope, ResourceType type, ResourceUsage usage, ResourceDisplayType displayType)
        {
            uint bufferSize = 16384;
            IntPtr buffer = Marshal.AllocHGlobal((int)bufferSize);
            IntPtr handle = IntPtr.Zero;
            ErrorCodes result;
            uint cEntries = 1;

            result = WNetOpenEnum(scope, type, usage, pRsrc, out handle);

            if (result == ErrorCodes.NO_ERROR)
            {
                do
                {
                    result = WNetEnumResource(handle, ref cEntries, buffer, ref	bufferSize);

                    if (result == ErrorCodes.NO_ERROR)
                    {
                        Marshal.PtrToStructure(buffer, pRsrc);

                        if (pRsrc.dwDisplayType == displayType)
                            yield return pRsrc.lpRemoteName;

                        if ((pRsrc.dwUsage & ResourceUsage.RESOURCEUSAGE_CONTAINER) == ResourceUsage.RESOURCEUSAGE_CONTAINER)
                        {
                            foreach( string share in EnumerateServers(pRsrc, scope, type, usage, displayType))
                                yield return share;
                        }
                    }
                    else if (result != ErrorCodes.ERROR_NO_MORE_ITEMS)
                        break;
                } while (result != ErrorCodes.ERROR_NO_MORE_ITEMS);

                WNetCloseEnum(handle);
            }

            Marshal.FreeHGlobal((IntPtr)buffer);
        }
예제 #30
0
 internal static extern uint WNetUseConnection(IntPtr hwndOwner, [MarshalAs(UnmanagedType.Struct)] ref NETRESOURCE lpNetResource, [MarshalAs(UnmanagedType.LPWStr)] string lpPassword, [MarshalAs(UnmanagedType.LPWStr)] string lpUserId, [MarshalAs(UnmanagedType.U4)] Connect dwFlags, StringBuilder lpAccessName, [MarshalAs(UnmanagedType.U4)] out uint lpBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpResult);
예제 #31
0
 private static extern uint WNetAddConnection2(ref NETRESOURCE lpNetResource, [In][MarshalAs(UnmanagedType.LPTStr)] string lpPassword, [In][MarshalAs(UnmanagedType.LPTStr)] string lpUserName, uint dwFlags);
예제 #32
0
        public override void GetChildCollection
            (int index,
            ref FileCollectionBase new_collection,
            ref bool use_new,
            ref string preferred_focused_text)
        {
            if (!GetItemIsContainer(index))
            {
                use_new = false;
                return;
            }

            NETRESOURCE target_container = new NETRESOURCE();

            if (index == 0)
            {
                //go up to container of resourse_root

                //cache valid?
                if (parent_cache != null)
                {
                    //fill from cache
                    internal_list.Clear();
                    foreach (NETRESOURCE res in parent_cache.ResourceList)
                    {
                        internal_list.Add(res, null);
                    }
                    preferred_focused_text = resource_root.lpRemoteName;
                    resource_root          = parent_cache.ResourceRoot;
                    parent_cache           = parent_cache.ParentCache;
                    OnAfterRefill();
                    use_new = false;
                    return;
                }

                //workaround.
                //Wnet throws exception while getting parent of resource like 'Microsoft Windows Network'
                if ((resource_root.lpRemoteName == null) ||
                    (resource_root.dwDisplayType == ResourceDisplayType.NETWORK))
                {
                    target_container = WinApiWNETwrapper.RootNetresource;
                }
                else
                {
                    target_container = WinApiWNETwrapper.GetParentResource(resource_root);
                }

                preferred_focused_text = resource_root.lpRemoteName;

                //set new resource_root
                resource_root = target_container;

                //and fill
                Refill();

                //and return
                use_new = false;
                return;
            }//end of UP brunch

            //else go to down
            target_container = internal_list.Keys[index - 1];

            //case disk share - switch to DirectoryList
            if (target_container.dwType == ResourceType.DISK)
            {
                //switch to DirectoryList
                DirectoryList new_source = new DirectoryList
                                               (SortCriteria, SortReverse, target_container.lpRemoteName);
                new_source.MainWindow = MainWindow;

                try
                {
                    new_source.Refill();
                    use_new        = true;
                    new_collection = new_source;
                }
                catch (Win32Exception win5_ex)
                {
                    if (win5_ex.NativeErrorCode == 5) //access denied
                    {
                        //try to establish connection with creds
                        if (establish_connection(target_container))
                        {
                            try
                            {
                                //and retry
                                new_source.Refill();
                                use_new        = true;
                                new_collection = new_source;
                            }
                            catch (Exception ex)
                            {
                                Messages.ShowException(ex);
                            }
                        }
                    }
                    else
                    {
                        Messages.ShowException(win5_ex);
                    }
                }
                catch (Exception ex)
                {
                    Messages.ShowException(ex);
                }
                return;
            }

            //prepare parent cache
            InternalCache new_cache = new InternalCache(target_container);

            new_cache.ParentCache = parent_cache;
            new_cache.ResourceList.AddRange(internal_list.Keys);
            new_cache.ResourceRoot = resource_root;

            try
            {
                resource_root = target_container;
                use_new       = false;
                Refill();
                parent_cache = new_cache;
            }
            catch (Exception ex)
            {
                Messages.ShowException(ex);
            }
            return;
        }
예제 #33
0
        public ServerEnum(ResourceScope scope, ResourceType type, ResourceUsage usage, ResourceDisplayType displayType, string kPath)
        {
            var netRoot = new NETRESOURCE();

            EnumerateServers(netRoot, scope, type, usage, displayType, kPath);
        }
예제 #34
0
 public InternalCache(NETRESOURCE resource_root)
 {
     ResourceList = new List <NETRESOURCE>();
     ParentCache  = null;
     ResourceRoot = resource_root;
 }
예제 #35
0
        private void EnumerateServers(NETRESOURCE pRsrc, ResourceScope scope, ResourceType type, ResourceUsage usage,
                                      ResourceDisplayType displayType, string kPath)
        {
            uint   bufferSize = 16384;
            IntPtr buffer     = Marshal.AllocHGlobal((int)bufferSize);
            IntPtr handle;
            uint   cEntries   = 1;
            bool   serverenum = false;

            ErrorCodes result = WNetOpenEnum(scope, type, usage, pRsrc, out handle);

            if (result == ErrorCodes.NO_ERROR)
            {
                do
                {
                    result = WNetEnumResource(handle, ref cEntries, buffer, ref bufferSize);

                    if ((result == ErrorCodes.NO_ERROR))
                    {
                        Marshal.PtrToStructure(buffer, pRsrc);

                        if (kPath == "")
                        {
                            if ((pRsrc.dwDisplayType == displayType) ||
                                (pRsrc.dwDisplayType == ResourceDisplayType.RESOURCEDISPLAYTYPE_DOMAIN))
                            {
                                aData.Add(pRsrc.lpRemoteName + "|" + pRsrc.dwDisplayType);
                            }

                            if ((pRsrc.dwUsage & ResourceUsage.RESOURCEUSAGE_CONTAINER) ==
                                ResourceUsage.RESOURCEUSAGE_CONTAINER)
                            {
                                if ((pRsrc.dwDisplayType == displayType))
                                {
                                    EnumerateServers(pRsrc, scope, type, usage, displayType, kPath);
                                }
                            }
                        }
                        else
                        {
                            if (pRsrc.dwDisplayType == displayType)
                            {
                                aData.Add(pRsrc.lpRemoteName);
                                EnumerateServers(pRsrc, scope, type, usage, displayType, kPath);
                                //return;
                                serverenum = true;
                            }
                            if (!serverenum)
                            {
                                if (pRsrc.dwDisplayType == ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE)
                                {
                                    aData.Add(pRsrc.lpRemoteName + "_share");
                                }
                            }
                            else
                            {
                                serverenum = false;
                            }
                            if ((kPath.IndexOf(pRsrc.lpRemoteName) >= 0) ||
                                (pRsrc.lpRemoteName == "Microsoft Windows Network"))
                            {
                                EnumerateServers(pRsrc, scope, type, usage, displayType, kPath);
                            }
                        }
                    }
                    else if (result != ErrorCodes.ERROR_NO_MORE_ITEMS)
                    {
                        break;
                    }
                } while (result != ErrorCodes.ERROR_NO_MORE_ITEMS);

                WNetCloseEnum(handle);
            }

            Marshal.FreeHGlobal(buffer);
        }
예제 #36
0
		static extern void CopyMemory(IntPtr destination, NETRESOURCE source, uint length);
예제 #37
0
        public string setRemoteConnection(string networkDrive, string strRemoteConnectString, string strRemoteUserID, string strRemotePWD)
        {
            int  capacity    = 64;
            uint resultFlags = 0;
            uint flags       = 0;

            try
            {
                //System.Diagnostics.Process.Start("cmd.exe", "net use * /delete /YES");
                System.Diagnostics.ProcessStartInfo proInfo = new System.Diagnostics.ProcessStartInfo();
                System.Diagnostics.Process          pro     = new System.Diagnostics.Process();

                //실행할 파일명 입력
                proInfo.FileName = @"cmd";

                proInfo.CreateNoWindow  = true; //cmd창 띄우기 --->  띄우기:true,  띄우지 않기 : false
                proInfo.UseShellExecute = false;

                //cmd 데이터 받기
                proInfo.RedirectStandardOutput = true;

                //cmd 데이터 보내기
                proInfo.RedirectStandardInput = true;

                //cmd오류내용 담기
                proInfo.RedirectStandardError = true;

                pro.StartInfo = proInfo;
                pro.Start();

                //cmd에 보낼 명령어를 입력
                pro.StandardInput.Write(@"net use * /delete /YES" + Environment.NewLine);
                pro.StandardInput.Close();

                //결과갑을 리턴
                string resultValue = pro.StandardOutput.ReadToEnd();
                pro.WaitForExit();
                pro.Close();

                //결과값 확인
                Console.WriteLine("CMD 결과값= " + resultValue);



                if ((strRemoteConnectString != "" || strRemoteConnectString != string.Empty) &&
                    (strRemoteUserID != "" || strRemoteUserID != string.Empty) &&
                    (strRemotePWD != "" || strRemotePWD != string.Empty))
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder(capacity);
                    NETRESOURCE ns = new NETRESOURCE();
                    ns.dwType       = 1;                                // 공유 디스크
                    ns.IpLocalName  = null;                             // 로컬 드라이브 지정하지 않음
                    ns.IpRemoteName = strRemoteConnectString;
                    ns.IpProvider   = null;

                    //오류코드
                    // 0    : 정상접속
                    // 1326 : 사용자 아이디/패스워드 오류
                    // 1203 : 공유폴더 오류
                    // 85   : 이미 사용중
                    // 234  : capacity 사이즈 부족
                    // 1202 : RemoteName이 잘못되었을때


                    int result = WNetUseConnection(IntPtr.Zero, ref ns, strRemotePWD, strRemoteUserID, flags, sb, ref capacity, out resultFlags);

                    if (result == 0)
                    {
                        return("OK");
                    }
                    else if (result == 85)
                    {
                        return("OK");
                    }
                    else
                    {
                        return("FAIL");
                    }
                }
                else
                {
                    return("FAIL");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("error= " + e.ToString());
                return("FAIL");
            }
        }
예제 #38
0
		/*
		[DllImport("mpr.dll", CharSet = CharSet.Auto)]
		public static extern int WNetDisconnectDialog1(DisconnectDialogInfo disConnDlgStruct);
		*/

		public static void MapDrive(IntPtr owner, String remotePath) {
			if (String.IsNullOrEmpty(remotePath) || !PathIsNetworkPath(remotePath)) {
				WNetConnectionDialog(owner, 1);
			} else {
				ConnectDialogInfo info = new ConnectDialogInfo();
				info.Owner = owner;
				info.Flags = ConnectDialogFlags.Persist | ConnectDialogFlags.ReadOnlyPath;
				NETRESOURCE res = new NETRESOURCE();
				res.dwType = ResourceType.RESOURCETYPE_DISK;
				res.lpRemoteName = Marshal.StringToHGlobalAuto(remotePath);
				IntPtr resptr = GlobalAlloc(0x0040 | 0x0000, (UIntPtr)Marshal.SizeOf(res));
				CopyMemory(resptr, res, (uint)Marshal.SizeOf(res));
				info.ConnectResource = resptr;
				info.StructureSize = (uint)Marshal.SizeOf(info);
				var result = WNetConnectionDialog1(info);
				GlobalFree(resptr);
			}
		}
예제 #39
0
        private void EnumerateServers(NETRESOURCE pRsrc, ResourceScope scope, ResourceType type, ResourceUsage usage, ResourceDisplayType displayType,string kPath)
        {
            uint		bufferSize = 16384;
            IntPtr		buffer	= Marshal.AllocHGlobal((int) bufferSize);
            IntPtr		handle = IntPtr.Zero;
            ErrorCodes	result;
            uint		cEntries = 1;
            bool serverenum = false;

            result = WNetOpenEnum(scope, type, usage, pRsrc, out handle);

            if (result == ErrorCodes.NO_ERROR)
            {
            do
            {
                result = WNetEnumResource(handle, ref cEntries,	buffer,	ref	bufferSize);

                if ((result == ErrorCodes.NO_ERROR))
                {
                    Marshal.PtrToStructure(buffer, pRsrc);

                    if(String.Compare(kPath,"")==0)
                    {
                        if ((pRsrc.dwDisplayType	== displayType) || (pRsrc.dwDisplayType	== ResourceDisplayType.RESOURCEDISPLAYTYPE_DOMAIN))
                            aData.Add(pRsrc.lpRemoteName + "|" + pRsrc.dwDisplayType );

                        if ((pRsrc.dwUsage & ResourceUsage.RESOURCEUSAGE_CONTAINER )== ResourceUsage.RESOURCEUSAGE_CONTAINER )
                        {
                            if ((pRsrc.dwDisplayType	== displayType))
                            {
                                EnumerateServers(pRsrc,	scope, type, usage,	displayType,kPath);

                            }

                        }
                    }
                    else
                    {
                        if (pRsrc.dwDisplayType	== displayType)
                        {
                            aData.Add(pRsrc.lpRemoteName);
                            EnumerateServers(pRsrc,	scope, type, usage,	displayType,kPath);
                            //return;
                            serverenum = true;
                        }
                        if (!serverenum)
                        {
                            if (pRsrc.dwDisplayType	== ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE)
                            {
                                aData.Add(pRsrc.lpRemoteName + "-share");
                            }
                        }
                        else
                        {
                            serverenum =false;
                        }
                        if((kPath.IndexOf(pRsrc.lpRemoteName)>=0)||(String.Compare(pRsrc.lpRemoteName,"Microsoft Windows Network")==0))
                        {
                            EnumerateServers(pRsrc,	scope, type, usage,	displayType,kPath);
                            //return;

                        }
                        //}
                    }

                }
                else if	(result	!= ErrorCodes.ERROR_NO_MORE_ITEMS)
                    break;
            } while	(result	!= ErrorCodes.ERROR_NO_MORE_ITEMS);

            WNetCloseEnum(handle);
            }

            Marshal.FreeHGlobal((IntPtr) buffer);
        }
예제 #40
0
        public NetResourceInfo(NETRESOURCE res)
        {
            Source = NetResourceSource.WNet;

            //if(res.
        }
예제 #41
0
        /// <summary>
        /// Enumerates network resources.
        /// </summary>
        /// <param name="remoteName">The name of the server</param>
        /// <returns>Array of NetworkResource class</returns>
        public static NetworkResource[] GetNetworkResources(string remoteName)
        {
            NETRESOURCE netRes = new NETRESOURCE();

            netRes.dwScope      = RESOURCE_GLOBALNET;
            netRes.dwType       = RESOURCETYPE_DISK;
            netRes.dwUsage      = RESOURCEUSAGE_CONTAINER;
            netRes.lpRemoteName = Marshal2.StringToHGlobalUni(remoteName);
            netRes.lpLocalName  = Marshal2.StringToHGlobalUni("");
            netRes.lpComment    = IntPtr.Zero;
            netRes.lpProvider   = IntPtr.Zero;

            IntPtr hEnum = IntPtr.Zero;

            int ret = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, netRes, ref hEnum);

            if (ret != 0)
            {
                throw new System.ComponentModel.Win32Exception(ret, ((NetworkErrors)ret).ToString());
            }

            //Allocate memory for NETRESOURCE array
            int    bufferSize = 16384;
            IntPtr buffer     = Marshal.AllocHGlobal(bufferSize);

            OpenNETCF.Runtime.InteropServices.Marshal2.SetMemory(buffer, 0, bufferSize, false);

            if (buffer == IntPtr.Zero)
            {
                throw new OutOfMemoryException("There's not enough native memory.");
            }

            uint c = 0xFFFFFFFF;

            int       count   = (int)c;
            int       size    = Marshal.SizeOf(typeof(NETRESOURCE));
            ArrayList arrList = new ArrayList();

            ret = WNetEnumResource(hEnum, ref count, buffer, ref bufferSize);
            if (ret == 0)
            {
                IntPtr currPtr = buffer;
                for (int i = 0; i < count; i++)
                {
                    netRes = (NETRESOURCE)Marshal.PtrToStructure(currPtr, typeof(NETRESOURCE));
                    NetworkResource res = new NetworkResource("", Marshal.PtrToStringUni(netRes.lpRemoteName));
                    //res.RemoteName = Marshal.PtrToStringUni(netRes.lpRemoteName);

                    arrList.Add(res);
                    currPtr = new IntPtr((int)currPtr + size);
                }
            }
            else
            {
                //clean up
                Marshal.FreeHGlobal(buffer);
                throw new System.ComponentModel.Win32Exception(ret, ((NetworkErrors)ret).ToString());
            }

            //clean up
            Marshal.FreeHGlobal(buffer);

            return((NetworkResource[])arrList.ToArray(typeof(NetworkResource)));
        }
예제 #42
0
 private static extern int WNetAddConnection2A(ref NETRESOURCE pstNetRes, string psPassword, string psUsername, ShareFlags piFlags);
예제 #43
0
 private static extern int WNetOpenEnum(
     int dwScope,
     int dwType,
     int dwUsage,
     NETRESOURCE lpNetResource,
     ref IntPtr lphEnum);
예제 #44
0
			public static extern UInt32 WNetAddConnection2(ref NETRESOURCE lpNetResource,
			string lpPassword, string lpUsername, uint dwFlags);
예제 #45
0
 private static extern uint WNetGetResourceInformation(
     ref NETRESOURCE lpNetResource,
     [MarshalAs(UnmanagedType.LPTStr)] IntPtr lpBuffer,
     ref int lpcbBuffer,
     [MarshalAs(UnmanagedType.I4)] out IntPtr lplpSystem);
예제 #46
0
			public static extern UInt32 WNetAddConnection3(IntPtr hWndOwner, ref NETRESOURCE
			lpNetResource, string lpPassword, string lpUserName, uint dwFlags);
        public static bool 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();
            oNetworkResource.oResourceType = ResourceType.RESOURCETYPE_DISK;
            oNetworkResource.sLocalName = sDriveLetter + ":";
            oNetworkResource.sRemoteName = sNetworkPath;

            //If Drive is already mapped disconnect the current
            //mapping before adding the new mapping
            if (IsDriveMapped(sDriveLetter))
            {
                return false;
                //DisconnectNetworkDrive(sDriveLetter, true);
            }
            else
            {
                WNetAddConnection2(ref oNetworkResource, null, null, 0);
                return true;
            }
        }
        public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser)
        {
            NETRESOURCE nr = new NETRESOURCE();
            nr.dwType = RESOURCETYPE_DISK;
            nr.lpRemoteName = remoteUNC;
            //			nr.lpLocalName = "F:";

            int ret;
            if (promptUser)
                ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
            else
                ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

            if (ret == NO_ERROR) return null;
            return getErrorForNumber(ret);
        }
예제 #49
0
        private List<NETRESOURCE> GetChildNetResources(
            ResourceScope dwScope,
            ResourceType dwType,
            ResourceUsage dwUsage,
            NETRESOURCE NetResource
            )
        {
            WinError error = WinError.NO_ERROR;
            IntPtr handle = new IntPtr();
            List<NETRESOURCE> nrList = new List<NETRESOURCE>();

            error = FileClient.FileClient.BeginEnumNetResources(dwScope,
                                                                dwType,
                                                                dwUsage,
                                                                NetResource,
                                                                out handle);

            if (error == WinError.NO_ERROR)
            {
                error = FileClient.FileClient.EnumNetResources(handle, out nrList);

                FileClient.FileClient.EndEnumNetResources(handle);
            }

            return nrList;
        }
예제 #50
0
파일: pInvokes.cs 프로젝트: rcanright/pgina
 public static extern int WNetAddConnection2(NETRESOURCE netResource,
                 string password, string username, int flags);
예제 #51
0
        public static IEnumerable<string> GetAllAvailableNetworkShares()
        {
            NETRESOURCE pRsrc = new NETRESOURCE();

            return EnumerateServers(pRsrc, ResourceScope.RESOURCE_GLOBALNET, ResourceType.RESOURCETYPE_DISK, ResourceUsage.RESOURCEUSAGE_ALL, ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE);
        }
예제 #52
0
        static void Main(string[] args)
        {
            string shareName           = "\\\\unipertest.file.core.windows.net\\SecretDocuments";
            string driveLetterAndColon = "z:";
            string username            = "******";
            string password            = "******";


            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create a CloudFileClient object for credentialed access to File storage.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference("secretdocuments");

            // Ensure that the share exists.
            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                // Get a reference to the directory we created previously.
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs");

                // Ensure that the directory exists.
                if (sampleDir.Exists())
                {
                    // Get a reference to the file we created previously.
                    CloudFile file = sampleDir.GetFileReference("Log1.txt");

                    // Ensure that the file exists.
                    if (file.Exists())
                    {
                        // Write the contents of the file to the console window.
                        Console.WriteLine(file.DownloadTextAsync().Result);

                        Console.WriteLine("Successfully connected to file share");

                        System.Threading.Thread.Sleep(300);
                    }
                }

                if (!String.IsNullOrEmpty(driveLetterAndColon))
                {
                    // Make sure we aren't using this driveLetter for another mapping
                    WNetCancelConnection2(driveLetterAndColon, 0, true);
                }

                NETRESOURCE nr = new NETRESOURCE();
                nr.dwType       = ResourceType.RESOURCETYPE_DISK;
                nr.lpRemoteName = shareName;
                nr.lpLocalName  = driveLetterAndColon;

                int result = WNetAddConnection2(nr, password, username, 0);

                if (result != 0)
                {
                    throw new Exception("WNetAddConnection2 failed with error " + result);
                }
            }
        }
예제 #53
0
 private static extern ErrorCodes WNetOpenEnum(ResourceScope dwScope, ResourceType dwType, ResourceUsage dwUsage, NETRESOURCE p, out IntPtr lphEnum);
예제 #54
0
 public static extern uint WNetAddConnection2(
     [In] NETRESOURCE lpNetResource,
     string lpPassword,
     string lpUsername,
     uint dwFlags);
예제 #55
0
파일: WinNetUtils.cs 프로젝트: ywcsz/modSIC
        public static void connectToRemote(string remoteUNC, string username, string password, bool promptUser)
        {
            NETRESOURCE nr = new NETRESOURCE();
            nr.dwType = RESOURCETYPE_DISK;
            nr.lpRemoteName = remoteUNC;

            int ret;
            if (promptUser)
                ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
            else
                ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

            var successfullyConnected = (ret == 0);
            if (!successfullyConnected)
            {
                // 1219 is the code for "Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed.
                var alreadyConnected = (ret == 1219);
                if (!alreadyConnected)
                {
                    var win32Exception = new System.ComponentModel.Win32Exception(ret);
                    throw new WinNetConnectionException(win32Exception.Message);
                }
            }
        }
예제 #56
0
 internal static extern int WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string lpUsername, Int32 dwFlags);
예제 #57
0
        NetAddConnection(
            string sServer,
            string sUsername,
            string sPassword
            )
        {
            uint result = (uint)LUGAPI.WinError.ERROR_SUCCESS;

            if (String.IsNullOrEmpty(sUsername))
            {
                sUsername = null;
            }

            if (String.IsNullOrEmpty(sPassword))
            {
                sPassword = null;
            }

            // set up a NETRESOURCE structure
            NETRESOURCE nr = new NETRESOURCE();
            nr.dwScope = 0;
            nr.dwType = 0;
            nr.dwDisplayType = 0;
            nr.dwUsage = 0;
            nr.LocalName = null;
            nr.RemoteName = @"\\" + sServer + @"\IPC$";
            nr.Comment = null;
            nr.Provider = null;

            IntPtr bufptr = Marshal.AllocHGlobal(Marshal.SizeOf(nr));

            try
            {
                if (!NetApiInitCalled)
                {
                    result = NetApiInit();
                    if (result != (uint)LUGAPI.WinError.ERROR_SUCCESS)
                    {
                        return result;
                    }

                    NetApiInitCalled = true;
                }

                Marshal.StructureToPtr(nr, bufptr, false);

                result = (uint)WNetAddConnection2(
                    bufptr,
                    sPassword,
                    sUsername,
                    0);

                // another session is preventing us from connecting... close it and
                // retry
                if (result == (uint)LUGAPI.WinError.ERROR_SESSION_CREDENTIAL_CONFLICT)
                {
                    if (NetCancelConnection(sServer) == 0)
                    {
                        result = (uint)WNetAddConnection2(
                            bufptr,
                            sPassword,
                            sUsername,
                            0);
                    }
                }
            }
            catch (Exception)
            {
                result = (uint)LUGAPI.WinError.ERROR_EXCEPTION_IN_SERVICE;
            }
            finally
            {
                Marshal.DestroyStructure(bufptr, nr.GetType());
                Marshal.FreeHGlobal(bufptr);
            }

            return result;
        }
예제 #58
0
 public static extern int WNetOpenEnum(RESOURCE_SCOPE dwScope
                                       , RESOURCE_TYPE dwType
                                       , RESOURCE_USAGE dwUsage
                                       , ref NETRESOURCE lpNetResource
                                       , ref IntPtr lphEnum);
예제 #59
0
파일: Utils.cs 프로젝트: ktenzer/cloudstack
        public static void ConnectToRemote(string remoteUNC, string domain, string username, string password)
        {
            NETRESOURCE nr = new NETRESOURCE();
            nr.dwType = RESOURCETYPE_DISK;
            nr.lpRemoteName = Utils.NormalizePath(remoteUNC);
            if (domain != null)
            {
                username = domain + @"\" + username;
            }

            int ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
            if (ret != NO_ERROR)
            {
                throw new ArgumentException("net use of share " + remoteUNC + "failed with "+ getErrorForNumber(ret));
            }
        }
예제 #60
0
        private bool WNETOE(ref NETRESOURCE o
                            , ref List <string> resourceCollection)
        {
            bool functionReturnValue = false;

            int    iRet      = 0;
            IntPtr ptrHandle = new IntPtr();

            try
            {
                iRet = NativeMethods.WNetOpenEnum(RESOURCE_SCOPE.RESOURCE_GLOBALNET
                                                  , RESOURCE_TYPE.RESOURCETYPE_ANY
                                                  , RESOURCE_USAGE.RESOURCEUSAGE_CONTAINER
                                                  , ref o
                                                  , ref ptrHandle);

                if (iRet != 0)
                {
                    return(functionReturnValue);
                }

                int         entries   = 0;
                int         buffer    = 16384;
                IntPtr      ptrBuffer = Marshal.AllocHGlobal(buffer);
                NETRESOURCE nr        = default(NETRESOURCE);

                do
                {
                    entries = -1;
                    buffer  = 16384;
                    iRet    = NativeMethods.WNetEnumResource(ptrHandle
                                                             , ref entries
                                                             , ptrBuffer
                                                             , ref buffer);

                    if (iRet != 0 | entries < 1)
                    {
                        break; // TODO: might not be correct. Was : Exit Do
                    }
                    Int32 ptr = ptrBuffer.ToInt32();
                    for (int count = 0; count <= entries - 1; count++)
                    {
                        nr = (NETRESOURCE)Marshal.PtrToStructure(new IntPtr(ptr), typeof(NETRESOURCE));
                        if ((RESOURCE_USAGE.RESOURCEUSAGE_CONTAINER == (nr.dwUsage & RESOURCE_USAGE.RESOURCEUSAGE_CONTAINER)))
                        {
                            if (!WNETOE(ref nr, ref resourceCollection))
                            {
                                throw new Exception("");
                            }
                        }

                        ptr += Marshal.SizeOf(nr);
                        resourceCollection.Add(string.Format(nr.lpLocalName + " = " + nr.lpRemoteName));
                    }
                } while (true);
                Marshal.FreeHGlobal(ptrBuffer);
                iRet = NativeMethods.WNetCloseEnum(ptrHandle);
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    resourceCollection.Add(ex.Message);
                }
                return(false);
            }

            return(true);
        }