I need to send documents to a network printer (\\myserver\\myprinter). I\'m using the System.Printing classes to print, and it works fine when it\'s from a Windows Service,
The Network Printing from ASP.Net/C# can be done using:
If the Network is configured for Domain Users and Printer is added to print server:
///
/// Does the actual impersonation.
///
/// The name of the user to act as.
/// The domain name of the user to act as.
/// The password of the user to act as.
private void ImpersonateValidUser(
string userName,
string domain,
string password )
{
WindowsIdentity tempWindowsIdentity = null;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
try
{
if ( RevertToSelf() )
{
if ( LogonUser(
userName,
domain,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref token ) != 0 )
{
if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 )
{
tempWindowsIdentity = new WindowsIdentity( tokenDuplicate );
impersonationContext = tempWindowsIdentity.Impersonate();
}
else
{
throw new Win32Exception( Marshal.GetLastWin32Error() );
}
}
else
{
throw new Win32Exception( Marshal.GetLastWin32Error() );
}
}
else
{
throw new Win32Exception( Marshal.GetLastWin32Error() );
}
}
finally
{
if ( token!= IntPtr.Zero )
{
CloseHandle( token );
}
if ( tokenDuplicate!=IntPtr.Zero )
{
CloseHandle( tokenDuplicate );
}
}
}
///
/// Reverts the impersonation.
///
private void UndoImpersonation()
{
if ( impersonationContext!=null )
{
impersonationContext.Undo();
}
}
private WindowsImpersonationContext impersonationContext = null;
First make an call to impersonate the user and then call the print function that would look like below:
if(ImpersonateValidUser("username", "domain", "password"))
{
PrintDetails();
UndoImpersonation();
}