Wnetaddconnection2 коды ошибок

I’m running into an issue when I try to call WNetAddConnection2 to a machine in which I already have a session to. This is expected, as you can only connect to a network resource with only one set of credentials. What I’m trying to do is catch this condition and automatically call WNetCancelConnection2 to disconnect all existing connections and then retry the WNetAddConnection2 call. When I run the below code I get these log messages:

DEBUG - WNetAddConnection2 returned 1219
DEBUG - Multiple credentials detected, disconnecting all current sessions
DEBUG - WNetCancelConnection2 returned 0
DEBUG - WNetAddConnection2 returned 1219

If I set dwFlags to CONNECT_UPDATE_PROFILE in WNetCancelConnection I get these log messages:

DEBUG - WNetAddConnection2 returned 1219
DEBUG - Multiple credentials detected, disconnecting all current sessions
DEBUG - WNetCancelConnection2 returned 2250
DEBUG - WNetAddConnection2 returned 1219

Here is my source, all help is appreciated!

networkName = @"\192.168.1.1";
var netResource = new NetResource()
{
    Scope = ResourceScope.GlobalNetwork,
    ResourceType = ResourceType.Disk,
    DisplayType = ResourceDisplaytype.Share,
    RemoteName = networkName
};

int result = WNetAddConnection2(netResource, credentials.Password, credentials.UserName, 0);

log.Debug("WNetAddConnection2 returned " + result);

if (result == 1219)
{
    log.Debug("Multiple credentials detected, disconnecting all current sessions");

    result = WNetCancelConnection2(networkName, 0, true);
    log.Debug("WNetCancelConnection2 returned " + result);

    result = WNetAddConnection2(netResource, credentials.Password, credentials.UserName, 0);
    log.Debug("WNetAddConnection2 returned " + result);
}

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    !
    Соблюдайте общие правила форума

    Пожалуйста, выделяйте текст программы тегом [сode=pas] … [/сode]. Для этого используйте кнопку [code=pas] в форме ответа или комбобокс, если нужно вставить код на языке, отличном от Дельфи/Паскаля.
    Указывайте точные версии Delphi и используемых сетевых библиотек.

    Не приветствуется поднятие старых тем. Если ваш вопрос перекликается со старой темой, то для вопроса лучше создать новую тему, а старую указать в первом сообщении с описанием взаимосвязи.


    Внимание:
    попытки открытия обсуждений реализации вредоносного ПО, включая различные интерпретации спам-ботов, наказывается предупреждением на 30 дней.
    Повторная попытка — 60 дней. Последующие попытки бан.
    Мат в разделе — бан на три месяца…


    Полезные ссылки:
    user posted image MSDN Library user posted image FAQ раздела user posted image Поиск по разделу user posted image Как правильно задавать вопросы


    Выразить свое отношение к модераторам раздела можно здесь: user posted image Krid, user posted image Rouse_

    >
    Использование функции WNetAddConnection2
    , Не удается подключить сетевой ресурс

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему

      


    Сообщ.
    #1

    ,
    17.11.09, 06:06

      Не удается подключить сетевой диск С на рабочей станции

      Когда я делаю так :

      ExpandedWrap disabled

        begin

          WNetConnectionDialog(Handle,RESOURCETYPE_DISK)

        end;

      Тогда все получается. Только такой вариант меня не устраивает

      А если делаю вот так :

      ExpandedWrap disabled

        begin

           NetResource.dwType       := RESOURCETYPE_DISK;

           NetResource.lpLocalName  := ‘Z:’;

           NetResource.lpRemoteName := ‘\10.57.112.5c’;

           NetResource.lpProvider   := »;

           IF (WNetAddConnection2(NetResource,»,»,CONNECT_UPDATE_PROFILE))<> NO_ERROR then

           showmessage(IntToStr(GetLastError()));

        end;

      Функция GetLastError возвращает код ошибки 53 — Сетевой путь не найден !
      Комп подключен в корпоративный домен Corp.организация.loc Доступ к диску С «Полный». IP пингуется.
      По команде «Пуск » — «Выполнить» \10.57.112.5С содержимое диска С открывается. Пробовал копировать файлы
      досовской командой Copy тоже не получается.Команда выполняется, ошибок не возникает , но файлы не копируются.
      Может есть какая то проблема в «Групповой политике безопасности» ? Я то могу подключить статически диск С: Но все таки интересно, почему так происходит.

      Сообщение отредактировано: Oleg2004 — 17.11.09, 13:42


      Gesha



      Сообщ.
      #2

      ,
      17.11.09, 12:46

        Извините меня, программисты, если я кого-то своим вопросом обидел. Я прочитал раздел «Как правильно задавать вопросы». Дело в том, что мне действительно очень нужно разобраться почему у меня не работает функция WNetAddConnection2().Поверте, я не собираюсь у кого-то выпытывать ума и сопоставлять примеры из учебников.

        0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

        0 пользователей:

        • Предыдущая тема
        • Delphi: Сетевое программирование
        • Следующая тема

        Рейтинг@Mail.ru

        [ Script execution time: 0,0370 ]   [ 16 queries used ]   [ Generated: 4.06.23, 13:17 GMT ]  

        WEC uses the following process to read remote event logs.
         

        1. Connect to the remote computer using the provided username and password
            • Error messages will have «WNetAddConnection2 failed with error: <error>»
        2. Connect to the remote registry
            • Error messages will have «eventLogRegistryKeyCheck: <error>»
            • Note: The Remote Registry service must be running on the remote computer.
        3. Check if the event log is present by opening the event log’s registry key.
            • Error messages will have «eventLogRegistryKeyCheck: <error>»
        4. Open the Event log
            • Error messages will have «OpenEventLog: <error>»
        5. Read the Event Log entries.

        Common scenarios with the error message.

        Unable to connect to the remote computer due to network issue:

          ERROR [Time] [Sensor] [Machine]:[Event Log] Source:Application Error in EventLogReader initialization ex=com.symantec.cas.ucf.sensors.OpenDeviceException: ERROR_CODE[1203]. WNetAddConnection2 failed with error: No network provider accepted the given network path.

        This error is usually caused by an networking/connectivity problem between the Collector machine and machine and the log host (target) machine. To resolve this problem, resolve the underlying network issue and the collector should start working normally.

        Unable to connect to the remote computer due to incorrect credentials:

          ERROR [Time] [Sensor] [Machine]:[Event Log] Source:Application Error in EventLogReader initialization ex=com.symantec.cas.ucf.sensors.OpenDeviceException: ERROR_CODE[1326]. WNetAddConnection2 failed with error: Logon failure: unknown user name or bad password.

          or

          ERROR_CODE[1312]. WNetAddConnection2 failed with error: A specified logon session does not exist. It may already have been terminated.

        These errors are usually resolved by entering correct credentials into the sensor configuration.

        Note: You may need to set the Monitored Host Account Name to

        <Computer IP><username> or <Computer Name><username>

        .
        Note: If you continue to receive this error but you are confident the credentials are correct please contact support.

        If the Remote Registry service is not running or is not accessible:

            ERROR [Time] [Sensor] [Machine]:[Event Log] Source:Application Error in EventLogReader initialization ex=com.symantec.cas.ucf.sensors.OpenDeviceException: ERROR_CODE[53]. eventLogRegistryKeyCheck failed with error: The network path was not found. 
            WARN [Time] [Sensor] [Machine]:[Event Log] Source:System Source:System Reopenning eventlog failed with exception: ERROR_CODE[1726]. OpenEventLog failed with error: The remote procedure call failed.


          Note: The event log registry key is: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesEventlog<Event log name>
          This error can be caused by the following problems:

          • The Event Log registry entry is not present.
            Contact Microsoft support if you find the registry key is missing.
             
          • The Event Log registry key is not readable due to a permission issue.
            Adjust permissions for the user that you have configured in your sensor settings to allow them access to the event log registry key. For assistance with this permissions issue please contact Microsoft support.
             
          • If you are running Microsoft Windows Server 2003 Service Pack 1 you may need to upgrade to Service Pack 2. Please see Microsoft KB article 906570:
            A custom program that uses the RegConnectRegistry function can no longer access the registry of a remote computer http://support.microsoft.com/kb/906570
             
          • The WEC Sensor configuration has listed the Host name incorrectly.
            Try listing a simple hostname instead of FQDN, or vice versa. The correct entry varies depending on your DNS or Hosts file entries.
             
          • The user is not in the local administrator group.
            Unless the target machine is a Domain Controller, the user that you enter into the sensor configuration must be in the local administrators group even if the user is a domain admin. For assistance adding a user to the Local Administrators group please contact Microsoft Support.
             
          • Be sure the Remote Registry service is running on the remote computer.
             

          ERROR [Time] [Sensor] [Machine]:[Event Log] Source:EventLogNotPresent Error in EventLogReader initialization ex=com.symantec.cas.ucf.sensors.OpenDeviceException: ERROR_CODE[997]. eventLogRegistryKeyCheck failed with error: Overlapped I/O operation is in progress.

        The registry is corrupt or damaged:
         

          WARN [Time] [Sensor] [Machine]:[Event Log] Source:Security Reader failed to open device with error: ERROR_CODE[1500]. EventLog.read
          failed with error: El archivo de registro de sucesos está dañado. Trying to reopen…

          The collector is trying to pull down the events, however the event log is damaged or corrupted and needs to be deleted. Follow these steps on how to delete the corrupted log file.
          In this example we will use the security log.

            1. Click on the start button and select Administrative Tools.
               
            2. Next, click on Event Viewer
               
            3. Right click on Security log and select Clear All Events.
               
            4. When asked to save your security log, click on Yes. Fill in a name for the folder, then click Save.
               
            5. The log is now removed from the affected system.
               
            6. Restart the agent and observe the event flow.

        If the user has permissions to connect remotely, but does not have permissions to other services

        User does not have permission’s to the registry:
        Application Reader can not access registry on target box. Make sure user [Username] has permission’s to access registry on [Computer Name].

        User does not have permission’s to resources (can be caused by trust relationship on domain, or the user is not a member of the domain):
        Application Reader failed to login into target box. Make sure sensor configuration has correct credentials and user [Username] has permission’s to access [Computer Name].

        HI Iam Using WnetConnection2 Api in C#.net and when compiling this its giving Invalid Address ,But its working in VB.net,Iam passing ip address

        This is the code Below

        using System;

        using System.Collections.Generic;

        using System.ComponentModel;

        using System.Data;

        using System.Drawing;

        using System.Text;

        using System.Windows.Forms;

        using System.Runtime.InteropServices;

        namespace AutoBackupTool

        {

        public struct NETRESOURCE1

        {

        long dwScope;

        public long dwType;

        long dwDisplayType;

        long dwUsage;

        public string lpLocalName;

        public string lpRemoteName;

        public string lpComment;

        string lpProvider;

        }

        public partial class Form2 : Form

        {

        public const long RESOURCETYPE_DISK = 1;

        [DllImport(«mpr.dll», EntryPoint = «WNetAddConnection2», CharSet = System.Runtime.InteropServices.CharSet.Unicode)]

        private static extern int WNetAddConnection2(ref NETRESOURCE1 lpNetResource, string lpPassword, string lpUserName, int dwFlags);

        public Form2()

        {

        InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

        string UNCPath = string.Empty;

        string DriveLetter = string.Empty;

        MapDrive(DriveLetter, UNCPath);

        }

        public void MapDrive(string DriveLetter, string UNCPath)

        {

        try

        {

        NETRESOURCE1 nr1 = new NETRESOURCE1();

        //string x1 = «\» + «\» + Sch_SystemName + «\d$»;

        string UNCPath1 =«\\172.27.48.156\d$»;

        nr1.lpLocalName = «c:»;

        nr1.lpRemoteName = UNCPath1;

        //nr.lpLocalName = DriveLetter & «:»

        string strUsername = «Administrator»;

        //(add parameters to pass this if necessary)

        string strPassword = «paone»;

        //(add parameters to pass this if necessary)

        nr1.dwType = RESOURCETYPE_DISK;

        //}

        int result1 = 0;

        //result = WNetAddConnection2(ref nr, strPassword, strUsername, 0);

        result1 = WNetAddConnection2(ref nr1, strPassword, strUsername, 0);

        if (result1 == 0)

        {

        MessageBox.Show(«System Connetced Successfully»);

        }

        else

        {

        //MessageBox.Show(«System Not Connetced Successfully»);

        }

        }

        catch(Exception e)

        {

        MessageBox.Show(e.ToString());

        }

        }

        //}

        }

        PLZ Help Me

        Thanks in Advance

        Sudhir Babu

        • Home
        • VBForums
        • Visual Basic
        • Visual Basic .NET
        • WNETAddConnection2 Error Codes.

        1. May 23rd, 2007, 01:08 PM


          #1

          smilbuta is offline

          Thread Starter


          Lively Member

          smilbuta's Avatar


          WNETAddConnection2 Error Codes.

          Hello community

          I am trying to decipher how to translate my error code i get when trying to connect. my error is 1168

          I have read over the getLastError method but i obviously dont know how to use it.

          here is an example of how i tried,

          Code:

          Public Function MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String, ByVal uName As String, ByVal pWord As String) As Boolean
                  Dim nr As NETRESOURCE
                  Dim strUsername As String
                  Dim strPassword As String
                  nr = New NETRESOURCE
          
          
                  nr.lpRemoteName = UNCPath
                  nr.lpLocalName = DriveLetter & ":"
          
                  nr.dwType = RESOURCETYPE_DISK
          
                  strUsername = uName
                  strPassword = pWord
          
                  Dim result As Integer
                  Try
                      result = WNetAddConnection2(nr, strPassword, strUsername, 0)
                  Catch ex As Exception
                      MessageBox.Show("error: " & vbCrLf & ex.Message.ToString)
                  End Try
          
                  If result = 0 Then
                      MessageBox.Show(result)
                      Return True
                  Else
                      MessageBox.Show(errmsg = GetLastError(result))
                      Return False
                  End If
              End Function

          Any advice would be most helpfull including a simple code example on how to pass the error value to the method.

          VB.Net uber-noob since04, Yeababy!


        • Home
        • VBForums
        • Visual Basic
        • Visual Basic .NET
        • WNETAddConnection2 Error Codes.


        Posting Permissions

        • You may not post new threads
        • You may not post replies
        • You may not post attachments
        • You may not edit your posts
        •  
        • BB code is On
        • Smilies are On
        • [IMG] code is On
        • [VIDEO] code is On
        • HTML code is Off

        Forum Rules


        Click Here to Expand Forum to Full Width

        Понравилась статья? Поделить с друзьями:
      • Wnaspi32 dll ошибка
      • Witcher 3 ошибка модов
      • Witcher 3 exe системная ошибка vcomp110 dll
      • Witcher 3 exe системная ошибка msvcr120 dll
      • Witcher 3 exe системная ошибка msvcp120 dll