Listing 1

	The first time you encounter the need to impersonate - to have your application do
	 something in another security context - it can be daunting. The code snippet below
	  comes from a Web service that uses the caller's context to access a file on the local
	   machine (and send back some data - not shown).


public string ReadFile( string strFileName )
{
	try
	{
		StringBuilder sbResult = new StringBuilder();

		// the web service is running as the system account and
		// anonymous access is disabled.
		// get the windows identity of the user who 
		// authenticated with the web service
		WindowsIdentity wi = (WindowsIdentity)User.Identity;

		// Now impersonate the user so that the web service can
		// access the file in the context of the user
		WindowsImpersonationContext wic =    wi.Impersonate();

		try
		{
			// Access the file in the context of the impersonated user
			FileStream stream = File.Open( strFileName, FileMode.Open,
			FileAccess.Read, FileShare.ReadWrite );

			StreamReader reader = new StreamReader( stream );

			string strBuffer;

			while( (strBuffer = reader.ReadLine()) != null )
				sbResult.Append( strBuffer );

			stream.Close();
		}
		catch( Exception ex )
		{
			System.Diagnostics.Debug.WriteLine( ex.Message );
			return ex.Message;
		}

		// Undo the impersonation and continue running in the context of the
		// account the web service is running as.
		wic.Undo();

		return sbResult.ToString();
	}
	catch( Exception ex )
	{
		System.Diagnostics.Debug.WriteLine( ex.Message );
		return ex.Message;
	}
}