Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 611767
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T17:49:12+00:00 2026-05-13T17:49:12+00:00

I would lke to programmatically enable and start the Net.Tcp Port Sharing Service in

  • 0

I would lke to programmatically enable and start the Net.Tcp Port Sharing Service in C#. I can easily start the service using the ServiceController class. However, how do I enable the service, which is disabled by default?

I found one recommendation online to set the following registry key to 2 as follows, which supposedly sets the service startup type to Automatic:

string path = "SYSTEM\\CurrentControlSet\\Services\\" + serviceName;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true)) {
    key.SetValue("Start", 2);
}

I tried this and while it did appear to change the startup type to Automatic, there must be more to it, as the service would not now start up (programmatically or manually). I had to reset the startup type manually through the services.msc to reset things, so that the service could be enabled and started up again.

Has anyone solved this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T17:49:12+00:00Added an answer on May 13, 2026 at 5:49 pm

    There is more than one way to do this, depending on how “pure” of a solution you want. Here are some options. Note that all of these solutions require administrative rights and must run in an elevated process.

    Use the command prompt via C#

    This will involve shelling out to sc.exe and changing the startup type of the service via command line arguments. This is similar to the solution you mention above except there is no registry hacking required.

    namespace Sample
    {
        using System;
        using System.Diagnostics;
        using System.Globalization;
    
        internal class ServiceSample
        {
            private static bool ChangeStartupType(string serviceName, string startupType)
            {
                string arguments = string.Format(
                    CultureInfo.InvariantCulture,
                    "config {0} start= {1}",
                    serviceName,
                    startupType);
                using (Process sc = Process.Start("sc.exe", arguments))
                {
                    sc.WaitForExit();
                    return sc.ExitCode == 0;
                }
            }
    
            private static void Main()
            {
                ServiceSample.ChangeStartupType("NetTcpPortSharing", "auto");
            }
        }
    }
    

    Use WMI

    This requires an assembly reference for System.Management.dll. Here we will use WMI functionality to ChangeStartMode for the service.

    namespace Sample
    {
        using System;
        using System.Globalization;
        using System.Management;
    
        internal class ServiceSample
        {
            private static bool ChangeStartupType(string serviceName, string startupType)
            {
                const string MethodName = "ChangeStartMode";
                ManagementPath path = new ManagementPath();
                path.Server = ".";
                path.NamespacePath = @"root\CIMV2";
                path.RelativePath = string.Format(
                    CultureInfo.InvariantCulture,
                    "Win32_Service.Name='{0}'",
                    serviceName);
                using (ManagementObject serviceObject = new ManagementObject(path))
                {
                    ManagementBaseObject inputParameters = serviceObject.GetMethodParameters(MethodName);
                    inputParameters["startmode"] = startupType;
                    ManagementBaseObject outputParameters = serviceObject.InvokeMethod(MethodName, inputParameters, null);
                    return (uint)outputParameters.Properties["ReturnValue"].Value == 0;
                }
            }
    
            private static void Main()
            {
                ServiceSample.ChangeStartupType("NetTcpPortSharing", "Automatic");
            }
        }
    }
    

    Use P/Invoke to Win32 APIs

    To some people, this is the most “pure” method, although it’s more tricky to get right. Basically you’ll want to call ChangeServiceConfig from .NET. However, this requires that you first call OpenService for the specified service and that requires calling OpenSCManager beforehand (and don’t forget to CloseServiceHandle when you’re done!).

    Note: This code is for demonstration purposes only. It does not contain any error handling and may leak resources. A proper implementation should use SafeHandle types to ensure proper cleanup and should add appropriate error checking.

    namespace Sample
    {
        using System;
        using System.ComponentModel;
        using System.Runtime.InteropServices;
    
        internal class ServiceSample
        {
            private const uint SC_MANAGER_CONNECT = 0x1;
            private const uint SERVICE_CHANGE_CONFIG = 0x2;
            private const uint STANDARD_RIGHTS_WRITE = 0x20000;
    
            private const uint SERVICE_NO_CHANGE = 0xFFFFFFFF;
    
            private const uint SERVICE_AUTO_START = 0x2;
            private const uint SERVICE_DEMAND_START = 0x3;
            private const uint SERVICE_DISABLED = 0x4;
    
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, uint dwDesiredAccess);
    
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);
    
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern bool ChangeServiceConfig(IntPtr hService, uint dwServiceType, uint dwStartType, uint dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword, string lpDisplayName);
    
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern bool CloseServiceHandle(IntPtr hSCObject);
    
            private static bool ChangeStartupType(string serviceName, uint startType)
            {
                IntPtr scManager = ServiceSample.OpenSCManager(null, null, ServiceSample.SC_MANAGER_CONNECT);
                IntPtr service = ServiceSample.OpenService(scManager, serviceName, ServiceSample.SERVICE_CHANGE_CONFIG | ServiceSample.STANDARD_RIGHTS_WRITE);
                bool succeeded = ServiceSample.ChangeServiceConfig(service, ServiceSample.SERVICE_NO_CHANGE, startType, ServiceSample.SERVICE_NO_CHANGE, null, null, IntPtr.Zero, null, null, null, null);
                ServiceSample.CloseServiceHandle(service);
                ServiceSample.CloseServiceHandle(scManager);
    
                return succeeded;
            }
    
            private static void Main()
            {
                ServiceSample.ChangeStartupType("NetTcpPortSharing", ServiceSample.SERVICE_AUTO_START);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Would it be possible to print Hello twice using single condition ? if condition
Would it be possible to show an image in full screen mode using silverlight.
Would it be possible to write a class that is virtually indistinguishable from an
Would it not make sense to support a set of languages (Java, Python, Ruby,
Would the following SQL remove also the index - or does it have to
Would having a nice little feature that makes it quicker to write code like
Would it be wwwroot, C, the root virtual directory where the assets are hosted,
Would a C++ CLI compiler be able to compile some large sets of C++
Would NTFS allocation blocks of 16KB or 32KB make compile time faster in comparison
Would it suppose any difference regarding overhead to write an import loading all the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.