Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i m running a query(query session ) in cmd.exe and reading in c# Process class and StreamReader.
i m getting following output in the string:

<img src="http://www.freeimagehosting.net/t/dkon1.jpg">image of whole string



SESSIONNAME USERNAME ID STATE TYPE DEVICE
services 0 Disc
console administrator 1 Active
rdp-tcp 65536 Listen



by using ReadLine() method i am reading it and adding it to a DataTable:
in line no.1, i m replacing multiple space by regex its ok.
but after that in line 2 or three, table structure gets changed.

for example line 2 come like :
services 0 Disc

i want that it should replace NA for the column value is not present. there is no escape character inside string. How i can accomplish this. please help me out
Posted
Comments
AmitGajjar 14-Aug-12 2:30am    
didn't get you. why you have different structure to store in single DataTable ? there must be design level issue.
arshad alam 14-Aug-12 2:47am    
see the image... that is whole string....

in the line no.1 after removing multiple space . its ok, but in line line.2 get strings come like:
services 0 Disc

instead of :
services NA 0 Disc NA NA
AmitGajjar 14-Aug-12 3:11am    
So you mean to say that between service and 0 there are 3 spaces ?
arshad alam 14-Aug-12 3:20am    
yes
AmitGajjar 14-Aug-12 4:13am    
use string.Replace("3 space"," Na ");

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace RDSessionHostEnumerator
{

    class SessionInfo
    {
        private string _sessionID = "";
        public string SessionID
        {
            get { return _sessionID; }
            set { _sessionID = value; }
        }
        private string _sessionState = "";
        public string SessionState
        {
            get { return _sessionState; }
            set { _sessionState = value; }
        }
        private string _sessionUser = "";
        public string SessionUser
        {
            get { return _sessionUser; }
            set { _sessionUser = value; }
        }

        private string _clientProtocolType= "";
        public string ClientProtocolType
        {
            get { return _clientProtocolType; }
            set { _clientProtocolType = value; }
        }

        private string _clientDeviceName = "";
        public string ClientDeviceName
        {
            get { return _clientDeviceName; }
            set { _clientDeviceName = value; }
        }


        private string _sessionName = "";
        public string SessionName
        {
            get { return _sessionName; }
            set { _sessionName = value; }
        }
        public SessionInfo()
        {
        }
        public SessionInfo(string sessionID, string sessionState, string sessionUser, string clientProtocolType, string clientDeviceName, string sessionName)
        {
            this.SessionID = sessionID;
            this.SessionState = sessionState;
            this.SessionUser = sessionUser;
            this.ClientProtocolType = clientProtocolType;
            this.ClientDeviceName = clientDeviceName;
            this.SessionName = sessionName;
        }
    }
    class Program
    {
        [DllImport("wtsapi32.dll", SetLastError = true)]
        static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);

        [DllImport("wtsapi32.dll")]
        static extern void WTSCloseServer(IntPtr hServer);

        [DllImport("wtsapi32.dll", SetLastError = true)]
        static extern Int32 WTSEnumerateSessions(
            IntPtr hServer,
            [MarshalAs(UnmanagedType.U4)] Int32 Reserved,
            [MarshalAs(UnmanagedType.U4)] Int32 Version,
            ref IntPtr ppSessionInfo,
            [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);

        [DllImport("wtsapi32.dll")]
        static extern void WTSFreeMemory(IntPtr pMemory);

        [StructLayout(LayoutKind.Sequential)]
        public struct WTS_SESSION_INFO
        {
            public Int32 SessionID;

            [MarshalAs(UnmanagedType.LPStr)]
            public String pWinStationName;

            public WTS_CONNECTSTATE_CLASS State;
        }
        [DllImport("Wtsapi32.dll")]
        public static extern bool WTSQuerySessionInformation(
            System.IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);
   
        public enum WTS_INFO_CLASS
        {
            WTSInitialProgram,
            WTSApplicationName,
            WTSWorkingDirectory,
            WTSOEMId,
            WTSSessionId,
            WTSUserName,
            WTSWinStationName,
            WTSDomainName,
            WTSConnectState,
            WTSClientBuildNumber,
            WTSClientName,
            WTSClientDirectory,
            WTSClientProductId,
            WTSClientHardwareId,
            WTSClientAddress,
            WTSClientDisplay,
            WTSClientProtocolType,
            WTSIdleTime,
            WTSLogonTime,
            WTSIncomingBytes,
            WTSOutgoingBytes,
            WTSIncomingFrames,
            WTSOutgoingFrames,
            WTSClientInfo,
            WTSSessionInfo
        };

        public enum WTS_CONNECTSTATE_CLASS
        {
            WTSActive,
            WTSConnected,
            WTSConnectQuery,
            WTSShadow,
            WTSDisconnected,
            WTSIdle,
            WTSListen,
            WTSReset,
            WTSDown,
            WTSInit
        }

        public IntPtr OpenServer(String Name)
        {
            IntPtr server = WTSOpenServer(Name);
            return server;
        }
        public void CloseServer(IntPtr ServerHandle)
        {
            WTSCloseServer(ServerHandle);
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            List<sessioninfo> sessionList = p.ListSessions("localhost");
            foreach (SessionInfo s in sessionList)
            {
                Console.WriteLine(s.SessionID);
                Console.WriteLine(s.SessionUser);
                Console.WriteLine(s.SessionState);
                Console.WriteLine(s.ClientProtocolType);
                Console.WriteLine(s.ClientDeviceName);
            }
        }

        public List<sessioninfo> ListSessions(String ServerName)
        {
            IntPtr server = IntPtr.Zero;
            List<sessioninfo> ret = new List<sessioninfo>();
            server = OpenServer(ServerName);

            try
            {
                IntPtr ppSessionInfo = IntPtr.Zero;
                uint bytes = 0;
                Int32 count = 0;
                Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);
                Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));

                Int64 current = (int)ppSessionInfo;

                if (retval != 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO));
                        current += dataSize;
                        string protocol="";
                        string client = "";
                        string userName = "";
                        GetClientName(server, si.SessionID, out client, out bytes);
                        GetProtocolType(server, si.SessionID, out protocol, out bytes);
                        GetUserName(server, si.SessionID, out userName, out bytes);

                        SessionInfo sinfo = new SessionInfo(si.SessionID.ToString(), si.State.ToString(), userName, protocol, client, si.pWinStationName);
                        ret.Add(sinfo);
                    }

                    WTSFreeMemory(ppSessionInfo);
                }
            }
            finally
            {
                CloseServer(server);
            }

            return ret;
        }

        public void GetProtocolType(IntPtr server, int SessionID, out string protocol, out uint bytes)
        {
            protocol = "";
            IntPtr protocolPtr = IntPtr.Zero;
            WTSQuerySessionInformation(server, SessionID, WTS_INFO_CLASS.WTSClientProtocolType, out protocolPtr, out bytes);
            int proto = Marshal.ReadInt32(protocolPtr);

            switch (proto)
            {
                case 0:
                    protocol = "Console";
                    break;

                case 1:
                    protocol = "System-Legacy";
                    break;
                case 2:
                    protocol = "RDP-TCP";
                    break;
            }

        }

        public void GetClientName(IntPtr server, int SessionID, out string client, out uint bytes)
        {

            IntPtr clientPtr = IntPtr.Zero;
            WTSQuerySessionInformation(server, SessionID, WTS_INFO_CLASS.WTSClientName, out clientPtr, out bytes);
            client = Marshal.PtrToStringAnsi(clientPtr);
        }

        public void GetUserName(IntPtr server, int SessionID, out string user, out uint bytes)
        {

            IntPtr userPtr = IntPtr.Zero;
            WTSQuerySessionInformation(server, SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes);
            user = Marshal.PtrToStringAnsi(userPtr);
        }
    }
}</sessioninfo></sessioninfo></sessioninfo></sessioninfo>
 
Share this answer
 
I think the best way would go away from command "query session"...

Hope this help you...

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace RDSessionHostEnumerator
{
 
    class Program
    {
        [DllImport("wtsapi32.dll", SetLastError = true)]
        static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);

        [DllImport("wtsapi32.dll")]
        static extern void WTSCloseServer(IntPtr hServer);

        [DllImport("wtsapi32.dll", SetLastError = true)]
        static extern Int32 WTSEnumerateSessions(
            IntPtr hServer,
            [MarshalAs(UnmanagedType.U4)] Int32 Reserved,
            [MarshalAs(UnmanagedType.U4)] Int32 Version,
            ref IntPtr ppSessionInfo,
            [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);

        [DllImport("wtsapi32.dll")]
        static extern void WTSFreeMemory(IntPtr pMemory);

        [StructLayout(LayoutKind.Sequential)]
        public struct WTS_SESSION_INFO
        {
            public Int32 SessionID;

            [MarshalAs(UnmanagedType.LPStr)]
            public String pWinStationName;

            public WTS_CONNECTSTATE_CLASS State;
        }

        public enum WTS_CONNECTSTATE_CLASS
        {
            WTSActive,
            WTSConnected,
            WTSConnectQuery,
            WTSShadow,
            WTSDisconnected,
            WTSIdle,
            WTSListen,
            WTSReset,
            WTSDown,
            WTSInit
        }

        public IntPtr OpenServer(String Name)
        {
            IntPtr server = WTSOpenServer(Name);
            return server;
        }
        public void CloseServer(IntPtr ServerHandle)
        {
            WTSCloseServer(ServerHandle);
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            List<wts_session_info> sessionList = p.ListSessions("localhost");
            foreach (WTS_SESSION_INFO s in sessionList)
            {
                Console.WriteLine(s.pWinStationName);
                Console.WriteLine(s.SessionID);
                Console.WriteLine(s.State);
            }
        }

        public List<wts_session_info> ListSessions(String ServerName)
        {
            IntPtr server = IntPtr.Zero;
            List<wts_session_info> ret = new List<wts_session_info>();
            server = OpenServer(ServerName);

            try
            {
                IntPtr ppSessionInfo = IntPtr.Zero;

                Int32 count = 0;
                Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);
                Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));

                Int64 current = (int)ppSessionInfo;

                if (retval != 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO));
                        current += dataSize;
                        ret.Add(si);
                    }

                    WTSFreeMemory(ppSessionInfo);
                }
            }
            finally
            {
                CloseServer(server);
            }

            return ret;
        }
    }
}
 
Share this answer
 
v2
Comments
arshad alam 17-Aug-12 4:21am    
how we can query for Type and Device
Kuthuparakkal 17-Aug-12 5:06am    
Building on it... will post ASAP

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900