Running and debugging a .NET application as Network Service in Visual Studio 2010
This post generated some interest on a discussion list so I’m re-posting here on my blog. Cutting a longer story short, the original poster wanted a way to start a process as Network Service rather than as the current Windows identity to mitigate the risk that you have more rights than you should have.
For those who have tried to use “runas” to achieve this you are left with the rather bleak message: “RUNAS ERROR: Unable to acquire user password”.

I’ll skip the reasons for this and go straight onto the solution. Create a dummy service using the Service Manager (sc.exe). This launches the application in the right session and is allowed to run as Network Service or even Local System (NT Authority\Local System).
@echo off
sc delete NetworkServiceCmd >nul:
sc create NetworkServiceCmd binpath= “cmd /K start c:\neverendingapp.exe” obj= “NT Authority\Network Service” >nul:
sc start NetworkServiceCmd >nul:
sc delete NetworkServiceCmd >nul:
Simply drop the above into a batch file and run it. You can then use “Attach to Process” in Visual Studio to attach to the process (don’t forget that your PDB’s must be in the same location as the assembly).

Here’s a screenshot of the debugger attached to my “NeverEndingApp” and viewing the current identity.

You need to manually kill off the process you started, you can use Task Manager as usual or here’s a macro I use that works in my scenario. You can attach this to a Keyboard Shortcut or even a Toolbar.
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.DiagnosticsPublic Module TerminateProcess
Public Function TerminateProcess()
Dim processes As EnvDTE.Processes = DTE.Debugger.LocalProcesses
Dim process As EnvDTE.ProcessFor Each process In processes
If (process.Name.ToLower().Contains(“neverendingapp.exe”)) Then
process.Terminate(True)
End If
NextEnd Function
End Module
I’m certain all the above can be improved on but I think all the basics are in here and customising it for your process is a challenge I’ll leave to the reader!


Add A Comment