Search code examples
c#automationconnection-stringsap-gui

How do I find my Connection String required to automate SAP GUI through a C# application?


I am trying to make a connection to SAP GUI through C#. For reference, I am using code found here: How do I automate SAP GUI with c#

I have added a reference to sapfewse.ocx and the corresponding using statement. Here is my code:

using SAPFEWSELib;

private void OpenSAP()
{
    GuiApplication Application;
    GuiConnection Connection;
    GuiSession Session;
                        
    Application = (GuiApplication)System.Activator.CreateInstance(Type.GetTypeFromProgID("SapGui.ScriptingCtrl.1"));

    // How do I find the connection string that I use to connect to SAP?
    Connection = Application.OpenConnectionByConnectionString("XXXXXXXXX", false, true);
    Session = (GuiSession)Connection.Sessions.Item(0);

    Session.TestToolMode = 1;

    ((GuiTextField)Session.ActiveWindow.FindByName("RSYST-MANDT", "GuiTextField")).Text = "XXX";
    ((GuiTextField)Session.ActiveWindow.FindByName("RSYST-BNAME", "GuiTextField")).Text = "XXXXXXXX";
    ((GuiTextField)Session.ActiveWindow.FindByName("RSYST-BCODE", "GuiPasswordField")).Text = "XXXXXXXX";
    ((GuiTextField)Session.ActiveWindow.FindByName("RSYST-LANGU", "GuiTextField")).Text = "XX";            
}

I am getting an error when I run this code saying

...connection broken

How can I be sure of the correct connection string to use? Where can I find the connection string that I use to connect to SAP? Or is there a better way than using the OpenConnectionByConnectionString() method?


Solution

  • Use this line of code: Connection = Application.OpenConnectionByConnectionString("/H/IP Address/S/3200", false, true);

    H: Host IP Address S: Host Port Number. Default is 3200. Check yours.