Click here to Skip to main content
16,005,178 members
Home / Discussions / C#
   

C#

 
GeneralRe: Configuration problem Pin
Guffa2-Jul-05 11:36
Guffa2-Jul-05 11:36 
GeneralRe: Configuration problem Pin
priyanraj2-Jul-05 21:04
priyanraj2-Jul-05 21:04 
GeneralRe: Configuration problem Pin
S. Senthil Kumar3-Jul-05 3:35
S. Senthil Kumar3-Jul-05 3:35 
GeneralRe: Configuration problem Pin
priyanraj4-Jul-05 7:18
priyanraj4-Jul-05 7:18 
Generalurgent help please Pin
amarsumanth2-Jul-05 7:09
amarsumanth2-Jul-05 7:09 
GeneralRe: urgent help please Pin
S. Senthil Kumar3-Jul-05 3:29
S. Senthil Kumar3-Jul-05 3:29 
GeneralRe: urgent help please Pin
Dave Kreskowiak3-Jul-05 14:17
mveDave Kreskowiak3-Jul-05 14:17 
GeneralRe: urgent help please Pin
ksanju10008-Jul-05 19:35
ksanju10008-Jul-05 19:35 
Hi I have some notes on this topic if you still getting problem pls tell me

5.7.6. Get current user name
This sample presents two different approaches to getting current user information.

Namespaces:
using System;
using System.Net;
using System.Security.Principal;

Code:
static void Main(string[] args)
{
// get info about current user using Environment class
Console.WriteLine(Environment.UserDomainName + @"\" + Environment.UserName);

// --------------------------

// get current user from WindowsIdentity class
WindowsIdentity user = WindowsIdentity.GetCurrent();
// output current user name
Console.WriteLine(user.Name.ToString());
}


5.7.7. Impersonate as another user
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

class ImpersonateUser
{
// this implementation doesn't handle GetLastError function to catch error messages, it should be implemented in standard application

// mapping of Win32 function to logon under another account
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);

// this will duplicate access token based on current user's one
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(
IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL,
ref IntPtr DuplicateTokenHandle);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);

static void Main(string[] args)
{
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int SecurityImpersonation = 2;
// handle of access token of current user
IntPtr token = IntPtr.Zero;
// new token based on the old one
IntPtr duplicateToken = IntPtr.Zero;

// this method returns handle to access token of user we want to use to logon, user is check just in local database
if (LogonUser("TestUser", ".", "Test1234]", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token))
{
// token is duplicated according to the token of impersonated user
if (DuplicateToken(token, SecurityImpersonation, ref duplicateToken))
{
Console.WriteLine("Current user name: " + WindowsIdentity.GetCurrent().Name);
// new identity is created
WindowsIdentity newIdentity = new WindowsIdentity(duplicateToken);
// !!!! This is the impersonation !!!!
WindowsImpersonationContext impersonatedUser = newIdentity.Impersonate();
Console.WriteLine("Current user name: " + WindowsIdentity.GetCurrent().Name);
// return to the old user
impersonatedUser.Undo();
Console.WriteLine("Current user name: " + WindowsIdentity.GetCurrent().Name);

// close handles to tokens
CloseHandle(token);
CloseHandle(duplicateToken);
}
else { Console.WriteLine("Error duplicate."); }
}
else { Console.WriteLine("Error logon."); }
}
}


5.7.10. List running processes and user accounts
Namespaces:
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Collections;
using System.Diagnostics;

Code:
class ListOfProcessAccounts
{
class ProcessIdentity
{
public Process Process;
public WindowsIdentity Identity;

public ProcessIdentity(Process process, WindowsIdentity identity)
{
this.Process = process;
this.Identity = identity;
}
}

[Flags]
enum TOKEN_ACCESS : uint
{
TOKEN_ASSIGN_PRIMARY = 0x0001,
TOKEN_DUPLICATE = 0x0002,
TOKEN_IMPERSONATE = 0x0004,
TOKEN_QUERY = 0x0008,
TOKEN_QUERY_SOURCE = 0x0010,
TOKEN_ADJUST_PRIVILEGES = 0x0020,
TOKEN_ADJUST_GROUPS = 0x0040,
TOKEN_ADJUST_DEFAULT = 0x0080,
TOKEN_ADJUST_SESSIONID = 0x0100,
TOKEN_READ = 0x00020000 | TOKEN_QUERY,
TOKEN_WRITE = 0x00020000 | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT,
TOKEN_EXECUTE = 0x00020000,
};

[DllImport("Advapi32.dll", SetLastError = true)]
extern static int OpenProcessToken(IntPtr processHandle, TOKEN_ACCESS desiredAccess, out IntPtr tokenHandle);

[DllImport("kernel32.dll", SetLastError = true)]
extern static bool CloseHandle(IntPtr handle);

static ProcessIdentity[] GetProcessesIdentities()
{
ArrayList list = new ArrayList();

foreach( Process process in Process.GetProcesses() )
{
try
{
IntPtr token = IntPtr.Zero;
if( OpenProcessToken(process.Handle, TOKEN_ACCESS.TOKEN_QUERY, out token) == 0 )
{
throw new ApplicationException("Can't open process token for: " + process.ProcessName);
}

list.Add(new ProcessIdentity(process, new WindowsIdentity(token)));
CloseHandle(token);
}
catch( Exception ex )
{
list.Add(new ProcessIdentity(process, null));
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}

return (ProcessIdentity[])list.ToArray(typeof(ProcessIdentity));
}

static void Main(string[] args)
{
ProcessIdentity[] normalProcIDs = GetProcessesIdentities();
foreach( ProcessIdentity procid in normalProcIDs )
{
if( procid.Identity != null )
{
Console.WriteLine("{0} running under {1}", procid.Process.ProcessName, procid.Identity.Name);
}
else
{
Console.WriteLine("{0} *probably* running under SYSTEM", procid.Process.ProcessName);
}
}
}
}


8. Network Operations
8.1.1. Retrieve DNS computer name
Code:
public static void Main(string[] args) {
Console.WriteLine(“DNS: {0}”, System.Net.Dns.GetHostByName(“LocalHost”).HostName);
}
8.1.2. Retrieve NetBIOS computer name
Code:
public static void Main(string[] args) {
Console.WriteLine(“NetBIOS: {0}”, System.Environment.MachineName);
}
8.1.3. Obtain IP address and host
Namespaces:
using System;
using System.Net;

Code:
static void Main(string[] args)
{
string host = Dns.GetHostName();
Console.WriteLine("Hostname is: {0}", host);
IPHostEntry entry = Dns.GetHostByName(host);
foreach (IPAddress ip in entry.AddressList)
{
Console.WriteLine("IP address: " + ip.ToString());
}
}
8.1.4. Send email in .NET environment
Namespaces:
using System;
using System.Web.Mail;

Code:
static void Main(string[] args)
{
MailMessage mailMsg = new MailMessage();
mailMsg.From = "jan.seda@skilldrive.com";
mailMsg.To = "jseda@microsoft.com";
mailMsg.Cc = "";
mailMsg.Bcc = "";
mailMsg.Subject = "Here goes a subject";
mailMsg.Body = "Here goes email body";
mailMsg.Priority = (MailPriority)1;
mailMsg.Attachments.Add(new MailAttachment("c:\\links.txt"));
SmtpMail.SmtpServer = "smarthost";
SmtpMail.Send(mailMsg);
}
8.1.5. Retrieve email from POP3 mail server
Namespaces:
using System;
using System.IO;
using System.Text;
using System.Net.Sockets;

Code:
public static void Main ()
{
const string host = "pop3.yourdomain.com";
const string user = "youruseraccount";
const string password = "yourpassword";

// tcp client for pop3
TcpClient tcp = new TcpClient();

// connect to host to port 110 (pop3)
tcp.Connect(host, 110);
NetworkStream netStream = tcp.GetStream();
StreamReader reader = new StreamReader(tcp.GetStream());

// allocate bytes for buffered read by TCP stream
string inBuffer = "";
// sent bytes to mail server
byte[] outBuffer;
// read data into the buffer
inBuffer = reader.ReadLine();

// output data read from server (usually name of mail server with welcome message)
Console.WriteLine(inBuffer);

// authorize to the server (USER userName)
outBuffer = Encoding.ASCII.GetBytes("USER " + user + "\r\n");
netStream.Write(outBuffer, 0, outBuffer.Length);

// response from server (OK)
inBuffer = reader.ReadLine();

// send password (PASS password)
outBuffer = Encoding.ASCII.GetBytes("PASS " + password + "\r\n");
netStream.Write(outBuffer, 0, outBuffer.Length);

// response from server (OK - login)
inBuffer = reader.ReadLine();

Console.WriteLine("---------------------- Authenticated to server ----------------------");

outBuffer = Encoding.ASCII.GetBytes("STAT" + "\r\n");
netStream.Write(outBuffer, 0, outBuffer.Length);

inBuffer = reader.ReadLine();
Console.WriteLine(inBuffer);

// retrieve first message from server (RETR messageNumber)
outBuffer = Encoding.ASCII.GetBytes("RETR 1" + "\r\n");
netStream.Write(outBuffer, 0, outBuffer.Length);

inBuffer = reader.ReadLine();
Console.WriteLine(inBuffer);
while (!inBuffer.Equals("."))
{
inBuffer = reader.ReadLine();
Console.WriteLine(inBuffer);
}

outBuffer = Encoding.ASCII.GetBytes("QUIT" + "\r\n");
netStream.Write(outBuffer, 0, outBuffer.Length);

// close tcp connection
tcp.Close();
}
9. File operations
9.1. General IO operations
9.1.1. Get executing application’s path with reflection
Code:
static void Main(string[] args)
{
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
Console.WriteLine(path);
}
9.1.2. Get executing application’s path
Code:
static void Main(string[] args)
{
// this shows application's path
Console.WriteLine(System.Windows.Forms.Application.StartupPath);
}
9.1.3. Classes working with file and directory information

9.1.4. Change file & folder attributes
Code:
using System;
using System.IO;

class ChangeAttrib
{
static void Main(string[] args)
{
// arg[0] represent path to files and folder where attributes will be changed
ChangeAttributes(args[0]);
}

public static void ChangeAttributes(string path)
{
DirectoryInfo dirInfo = new DirectoryInfo(path);

// set directory attribute to appropriate
dirInfo.Attributes = FileAttributes.Normal;
foreach (FileSystemInfo file in dirInfo.GetFileSystemInfos())
{
// here set appropriate attribute for file
file.Attributes = FileAttributes.Normal;
}

foreach (DirectoryInfo dir in dirInfo.GetDirectories())
{
// do recursive calls to change attributes in subdirectories
ChangeAttributes(dir.FullName);
}
}
}
9.1.5. Recursive list of directories/subdirectories & files
Code:
using System;
using System.IO;

class Sample
{
static void Main(string[] args)
{
DirectoryInfo dirInfo = new DirectoryInfo("c:\\Sample_path");
RecursiveList(dirInfo);
}

private static void RecursiveList(DirectoryInfo dirInfo)
{
// first list all subdirectories
DirectoryInfo[] subDirs = dirInfo.GetDirectories();
foreach(DirectoryInfo subDir in subDirs)
{
RecursiveList(subDir);
}

// list all files in current directory (as RecursiveList method is called)
FileInfo[] dirFiles = dirInfo.GetFiles();
foreach(FileInfo fileInfo in dirFiles)
{
Console.WriteLine(fileInfo.FullName);
}
}
}


hope this will help
Regards,
sanjeev
GeneralRichttextbox - Fontstyles Pin
moon442-Jul-05 6:12
moon442-Jul-05 6:12 
GeneralRe: Richttextbox - Fontstyles Pin
Dario Solera2-Jul-05 6:24
Dario Solera2-Jul-05 6:24 
GeneralRe: Richttextbox - Fontstyles Pin
moon442-Jul-05 7:54
moon442-Jul-05 7:54 
GeneralRe: Richttextbox - Fontstyles Pin
Dario Solera2-Jul-05 22:30
Dario Solera2-Jul-05 22:30 
Question2nd code for - boolean error ? Pin
fracalifa2-Jul-05 0:56
fracalifa2-Jul-05 0:56 
AnswerRe: 2nd code for - boolean error ? Pin
leppie2-Jul-05 6:35
leppie2-Jul-05 6:35 
AnswerRe: 2nd code for - boolean error ? Pin
Robert Rohde2-Jul-05 6:50
Robert Rohde2-Jul-05 6:50 
GeneralRe: 2nd code for - boolean error ? Pin
fracalifa2-Jul-05 7:01
fracalifa2-Jul-05 7:01 
GeneralRe: 2nd code for - boolean error ? Pin
Guffa2-Jul-05 7:22
Guffa2-Jul-05 7:22 
GeneralRe: 2nd code for - boolean error ? Pin
DavidNohejl2-Jul-05 7:31
DavidNohejl2-Jul-05 7:31 
AnswerOT Pin
DavidNohejl2-Jul-05 6:57
DavidNohejl2-Jul-05 6:57 
GeneralRe: OT Pin
fracalifa2-Jul-05 7:04
fracalifa2-Jul-05 7:04 
GeneralRe: OT Pin
DavidNohejl2-Jul-05 7:17
DavidNohejl2-Jul-05 7:17 
GeneralRe: OT Pin
Colin Angus Mackay3-Jul-05 1:36
Colin Angus Mackay3-Jul-05 1:36 
Questionerror in bool condition ? Pin
fracalifa1-Jul-05 23:45
fracalifa1-Jul-05 23:45 
AnswerRe: error in bool condition ? Pin
Dario Solera1-Jul-05 23:52
Dario Solera1-Jul-05 23:52 
AnswerRe: error in bool condition ? Pin
Robert Rohde2-Jul-05 0:04
Robert Rohde2-Jul-05 0:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.