Password Encrypt and Decrypt Utility

Password Encrypt and Decrypt Utility

Developing a secure application you need to apply security features, like securing your password. Explaining the how to encrypt and decrypt password. First create static class name is PasswordUtility. Here I am using SHA1 algorithm you can use the MD5 algorithm also. This is 16 bit encryption.

public static class PasswordUtility

{

private static string strPassPhrase = “pa$$w0rd”;// can be any string

private static string strSaltValue = “s@1tValue”;// can be any string

private static string strHashAlgorithm = “SHA1”;// can be “MD5”

private static int intPasswordIterations = 2; // can be any number

private static string strInitVector = “@1B2c3D4e5F6g7H8”;

// must be 16 bytes

private static int intKeySize = 128; // can be 192 or 128

// Here calling Encrypt method, the given string(password)

// Parameter string to encrypt

//return type is encrypted password

public static string Encrypt(string plainPassword)

{

return Encrypt(plainPassword, strPassPhrase, strSaltValue, strHashAlgorithm, intPasswordIterations, strInitVector, intKeySize);

}

// Encrypt the given string(password)

//Parameters are Password to encrypt,can be any string,can be any //string,MD5,no of iterations,must be 16 bytes,keysize 256,128 or 192

//Return type encrypted value

public static string Encrypt(string plainText,

string passPhrase,

string saltValue,

string hashAlgorithm,

int passwordIterations,

string initVector,

int keySize)

{

// Convert strings into byte arrays.

// Let us assume that strings only contain ASCII codes.

// If strings include Unicode characters, use Unicode, UTF7, or UTF8

// encoding.

byte[] byInitVectorBytes = Encoding.ASCII.GetBytes(strInitVector);

byte[] bySaltValueBytes = Encoding.ASCII.GetBytes(strSaltValue);

// Convert our plaintext into a byte array.

// Let us assume that plaintext contains UTF8-encoded characters.

byte[] byPlainTextBytes = Encoding.UTF8.GetBytes(plainText);

// First, we must create a password, from which the key will be derived.

// This password will be generated from the specified passphrase and

// salt value. The password will be created using the specified hash

// algorithm. Password creation can be done in several iterations.

PasswordDeriveBytes password = new PasswordDeriveBytes(

passPhrase,

bySaltValueBytes,

hashAlgorithm,

passwordIterations);

// Use the password to generate pseudo-random bytes for the encryption

// key. Specify the size of the key in bytes (instead of bits).

byte[] byKeyBytes = password.GetBytes(keySize / 8);

// Create uninitialized Rijndael encryption object.

RijndaelManaged symmetricKey = new RijndaelManaged();

// It is reasonable to set encryption mode to Cipher Block Chaining

// (CBC). Use default options for other symmetric key parameters.

symmetricKey.Mode = CipherMode.CBC;

// Generate encryptor from the existing key bytes and initialization

// vector. Key size will be defined based on the number of the key

// bytes.

ICryptoTransform encryptor = symmetricKey.CreateEncryptor(

byKeyBytes,

byInitVectorBytes);

// Define memory stream which will be used to hold encrypted data.

MemoryStream memoryStream = new MemoryStream();

// Define cryptographic stream (always use Write mode for encryption).

CryptoStream cryptoStream = new CryptoStream(memoryStream,

encryptor,

CryptoStreamMode.Write);

// Start encrypting.

cryptoStream.Write(byPlainTextBytes, 0, byPlainTextBytes.Length);

// Finish encrypting.

cryptoStream.FlushFinalBlock();

// Convert our encrypted data from a memory stream into a byte array.

byte[] byCipherTextBytes = memoryStream.ToArray();

// Close both streams.

memoryStream.Close();

cryptoStream.Close();

// Convert encrypted data into a base64-encoded string.

string strCipherText = Convert.ToBase64String(byCipherTextBytes);

// Return encrypted string.

return strCipherText;

}

//Calling Decrypts method the given string(password)

//Parameter is Encrypted string

//Retrun type is decrypted string

// If condition was added to check empty and null

public static string Decrypt(string encryptedPassword)

{

if (encryptedPassword == “” || encryptedPassword == null)

return string.Empty;

return Decrypt(encryptedPassword, strPassPhrase, strSaltValue, strHashAlgorithm, intPasswordIterations, strInitVector, intKeySize);

}

public static string Decrypt(string cipherText,

string passPhrase,

string saltValue,

string hashAlgorithm,

int passwordIterations,

string initVector,

int keySize)

{

// Convert strings defining encryption key characteristics into byte

// arrays. Let us assume that strings only contain ASCII codes.

// If strings include Unicode characters, use Unicode, UTF7, or UTF8

// encoding.

byte[] byInitVectorBytes = Encoding.ASCII.GetBytes(strInitVector);

byte[] bySaltValueBytes = Encoding.ASCII.GetBytes(strSaltValue);

// Convert our ciphertext into a byte array.

byte[] byCipherTextBytes = Convert.FromBase64String(cipherText);

// First, we must create a password, from which the key will be

// derived. This password will be generated from the specified

// passphrase and salt value. The password will be created using

// the specified hash algorithm. Password creation can be done in

// several iterations.

PasswordDeriveBytes password = new PasswordDeriveBytes(

passPhrase,

bySaltValueBytes,

hashAlgorithm,

passwordIterations);

// Use the password to generate pseudo-random bytes for the encryption

// key. Specify the size of the key in bytes (instead of bits).

byte[] byKeyBytes = password.GetBytes(keySize / 8);

// Create uninitialized Rijndael encryption object.

RijndaelManaged symmetricKey = new RijndaelManaged();

// It is reasonable to set encryption mode to Cipher Block Chaining

// (CBC). Use default options for other symmetric key parameters.

symmetricKey.Mode = CipherMode.CBC;

// Generate decryptor from the existing key bytes and initialization

// vector. Key size will be defined based on the number of the key

// bytes.

ICryptoTransform decryptor = symmetricKey.CreateDecryptor(

byKeyBytes,

byInitVectorBytes);

// Define memory stream which will be used to hold encrypted data.

MemoryStream memoryStream = new MemoryStream(byCipherTextBytes);

// Define cryptographic stream (always use Read mode for encryption).

CryptoStream cryptoStream = new CryptoStream(memoryStream,

decryptor,

CryptoStreamMode.Read);

// Since at this point we don’t know what the size of decrypted data

// will be, allocate the buffer long enough to hold ciphertext;

// plaintext is never longer than ciphertext.

byte[] byPlainTextBytes = new byte[byCipherTextBytes.Length];

// Start decrypting.

int iDecryptedByteCount = cryptoStream.Read(byPlainTextBytes, 0, byPlainTextBytes.Length);

// Close both streams.

memoryStream.Close();

cryptoStream.Close();

// Convert decrypted data into a string.

// Let us assume that the original plaintext string was UTF8-encoded.

string strPlainText = Encoding.UTF8.GetString(byPlainTextBytes, 0, iDecryptedByteCount);

// Return decrypted string.

return strPlainText;

}

}//Class ends here

You can call the these methods like this

PasswordUtility.Encrypt(strUserPwd)

PasswordUtility.Decrypt(strUserPwd)

Generating the Random Key in c#

Enum CharacterType for random key.

enum CharacterType

{

UpperCase,

LowerCase,

Number,

Special

}

public static class KeyGenerator

{

private static readonly char[] _Letters = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”.ToCharArray();

private static readonly char[] _Numbers = “1234567890”.ToCharArray();

private static readonly char[] _Symbols = “!@#$%^&*.?”.ToCharArray();

public static string GenerateRandomKey(int minimumLength, int maximumLength,

bool allowCharacters, bool allowNumbers, bool allowSymbols)

{

string[] _CharacterTypes;

_CharacterTypes = getCharacterTypes(allowCharacters, allowNumbers, allowSymbols);

StringBuilder randomKey = new StringBuilder(maximumLength);

int currentRandomKeyLength = RandomNumber.Next(maximumLength);

if (currentRandomKeyLength < minimumLength)

{

currentRandomKeyLength = minimumLength;

}

//Generate the randomKey

for (int i = 0; i < currentRandomKeyLength; i++)

{

randomKey.Append(getCharacter(_CharacterTypes));

}

return randomKey.ToString();

}

public static string GenerateRandomKey()

{

return GenerateRandomKey(10, 10, true, true, true);

}

// Getting character types allowed in the key //(UpperCase,LowerCase,Number,Special)

//Parameters

//Whether to allow characters

//Whether to allow numbers

//Whether to allow symbols

//Return type as string array.

private static string[] getCharacterTypes(bool allowCharacters, bool allowNumbers, bool allowSymbols)

{

ArrayList alCharacterTypes = new ArrayList();

foreach (string characterType in Enum.GetNames(typeof(CharacterType)))

{

CharacterType currentType =

(CharacterType)Enum.Parse(typeof(CharacterType),

characterType, false);

bool addType = false;

switch (currentType)

{

case CharacterType.LowerCase:

addType = allowCharacters;

break;

case CharacterType.Number:

addType = allowNumbers;

break;

case CharacterType.Special:

addType = allowSymbols;

break;

case CharacterType.UpperCase:

addType = allowCharacters;

break;

}

if (addType)

{

alCharacterTypes.Add(characterType);

}

}

return (string[])alCharacterTypes.ToArray(typeof(string));

}

// Getting character type randomly from the array of character types

//Parameter is Array of allowed character types.

// One of the types as string

private static string getCharacter(string[] characterTypes)

{

string characterType =

characterTypes[RandomNumber.Next(characterTypes.Length)];

CharacterType typeToGet =

(CharacterType)Enum.Parse(typeof(CharacterType), characterType, false);

switch (typeToGet)

{

case CharacterType.LowerCase:

return _Letters[RandomNumber.Next(_Letters.Length)].ToString().ToLower();

case CharacterType.UpperCase:

return _Letters[RandomNumber.Next(_Letters.Length)].ToString().ToUpper();

case CharacterType.Number:

return _Numbers[RandomNumber.Next(_Numbers.Length)].ToString();

case CharacterType.Special:

return _Symbols[RandomNumber.Next(_Symbols.Length)].ToString();

}

return null;

}

}

Regular Expression in .Net

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Text.RegularExpressions;

namespace  PubishApps

{

/************************************************

* Topic : Usage of RegularExpression in .Net

* Reference System.Text.RegularExpressions.

* Author : kalit sikka

* Summary: This regex helper class is design to provide set of static methods to validate commonly used patterns like Email-ID, URL, IP Address, Social Security number, Zip codes etc.

* You just need to add this .cs file in your project to use any of the method in it.

* For : http://eggheadcafe.com

* **********************************************/

/// <summary> /// This helper class contain general regex static methods which in today to today coding tasks /// </summary> public class RegexHelper

{

public static bool IsValidEmailID(string sEmailID)

{

Regex oEmail = new Regex(@”^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$”); return oEmail.IsMatch(sEmailID);

}

public static bool IsValidURL(string sUrl)

{

Regex oURL = new Regex(@”^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$”); // you add more here like au, in return oURL.IsMatch(sUrl);

}

public static bool IsValidPhoneNumber(string sPhone)

{

Regex oPhone = new Regex(@”^[2-9]\d{2}-\d{3}-\d{4}$”); // US Phone – like 800-555-5555 | 333-444-5555 | 212-666-1234 return oPhone.IsMatch(sPhone);

}

public static bool IsValidIndianMobile(string sMobile)

{

Regex oMobile = new Regex(@”^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}98(\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$”); // Indian Mobile – like +919847444225 | +91-98-44111112 | 98 44111116 return oMobile.IsMatch(sMobile);

}

public static bool IsValidUKMobile(string sMobile)

{

Regex oMobile = new Regex(@”^07([\d]{3})[(\D\s)]?[\d]{3}[(\D\s)]?[\d]{3}$”); // UK Mobile – like 07976444333 | 07956-514333 | 07988-321-213 return oMobile.IsMatch(sMobile);

}

public static bool IsValidUSZipCode(string sZipCode)

{

Regex oZipCode = new Regex(@”^\d{5}$”); // ZipCode – like 33333 | 55555 | 23445 return oZipCode.IsMatch(sZipCode);

}

public static bool IsValidIPAddress(string sIPAddress)

{

Regex oIP = new Regex(@”^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$”); // IP Address – like 127.0.0.1 | 255.255.255.0 | 192.168.0.1 return oIP.IsMatch(sIPAddress);

}

public static bool IsValidTime(string sTime)

{

Regex oTime = new Regex(@”^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$”); return oTime.IsMatch(sTime);

}

public static bool Is24HourTimeFormat(string sTime)

{

Regex oTime = new Regex(@”^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$”); // like – 12:15 | 10:26:59 | 22:01:15 – Seconds are optional here return oTime.IsMatch(sTime);

}

public static bool Is12HourTimeFormat(string sTime)

{

Regex oTime = new Regex(@” ^ *(1[0-2]|[1-9]):[0-5][0-9] *(a|p|A|P)(m|M) *$”); // like – 12:00am | 1:00 PM | 12:59 pm return oTime.IsMatch(sTime);

}

public static bool DataFormat(string sDate)

{

// dd/MM/yyyy format with leap year validations Regex oDate = new Regex(@”^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((1[6-9]|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((1[6-9]|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((1[6-9]|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$”); return oDate.IsMatch(sDate);

}

public static bool IsNumeric(string sNum)

{

// Natural Number Regex oNum = new Regex(@”0*[1-9][0-9]*”); return oNum.IsMatch(sNum);

}

public static bool IsAlpha(string sValue)

{

// Alpha value Regex oValue = new Regex(@”[^a-zA-Z]”); return oValue.IsMatch(sValue);

}

public static bool IsAlphaNumeric(string strToCheck)

{

Regex oCheck=new Regex(“[^a-zA-Z0-9]”); return oCheck.IsMatch(strToCheck);

}

public static bool IsStrongPassword(string sPassword)

{

// Check Password with atleast 8 characters, no more than 15 characters, and must include atleast one upper case letter, one lower case letter, and one numeric digit. Regex oPassword = new Regex(@”^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$”); return oPassword.IsMatch(sPassword);

}

public static bool IsSocialSecurityNumber(string sValue)

{

// U.S. social security numbers, within the range of numbers that have been currently allocated Regex oValue = new Regex(@”^(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -]?)(?!00)\d\d\3(?!0000)\d{4}”); return oValue.IsMatch(sValue);

}

public static bool IsVISACreditCard(string sValue)

{

// Validate against a visa card number Regex oValue = new Regex(@”^([4]{1})([0-9]{12,15})$”); return oValue.IsMatch(sValue);

}

public static bool IsISBNumber(string sValue)

{

// ISBN validation expression Regex oValue = new Regex(@”^\d{9}[\d|X]$”); return oValue.IsMatch(sValue);

}

public static bool IsDollarAmount(string sAmt)

{

// Dollar decimal amount with or without dollar sign Regex oAmt = new Regex(@”^\$?\d+(\.(\d{2}))?$”); return oAmt.IsMatch(sAmt);

}

/// <summary> /// Method to return string array of splitted values from string /// </summary> /// <param name=”value”>string value [Kabir|Sachin|John|Mark|David|kevin|Nash]</param> /// <param name=”separator”>separator in the string value</param> /// <returns></returns> public static string[] mSplitString(string value, string separator)

{

string[] values = new string[25]; if(!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(separator))

{

values = System.Text.RegularExpressions.

Regex.Split(value, separator); return values;

}

return null;

}

/// <summary> /// To Remove specfic string from Collection of string /// </summary> /// <param name=”strNames”>Kabir|Sachin|John|Mark|David|kevin|Nash</param> /// <param name=”sep”>separator in the string value</param> /// <returns></returns> public static string mRemoveStringFromCollection(string strNames, string sep, string specificStr)

{

List<string> list = new List<string>(); string strValue = String.Empty; if (!string.IsNullOrEmpty(strNames))

{

list.AddRange(

Regex.Split(strNames, sep)); foreach (string str in list)

{

if (!str.Contains(specificStr))

{

if (string.IsNullOrEmpty(strValue))

{

strValue = str;

}

else

{

strValue = strValue + sep + str;

}

}

}

return strValue;

}

return strNames;

}

}

}

Extract Email addresses from given web url

protected void Button1_Click(object sender, EventArgs e)

{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“http://eggheadcafe.com/aboutus.aspx&#8221;); // Create WebRequest HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Initialise the connection StreamReader reader = new StreamReader(response.GetResponseStream()); // Start receving the Response and store it in to Stream and pass it to Stream reader string responseText = reader.ReadToEnd(); // Here we will apply regualr expression to responseText Regex re = new Regex(@”\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”); //string pattern is Email validation Expressioin MatchCollection me = re.Matches(responseText); String str = string.Empty; foreach(Match m in me)

{

str += m.Value +

” , ” ;

}

Response.Write(str);

}

List SQL Server databases in C#.net

How to List SQL Server databases in C#.net

 

using System.Data;
using System.Data.SqlClient;

// change your connection string below in connString
String connString =
“Data Source=LegalServer; Integrated Security=True;”;

using (SqlConnection sqlConx = new SqlConnection (connString))
{
sqlConx.Open();
DataTable tblDatabases = sqlConx.GetSchema (“Databases”);
sqlConx.Close();

foreach (DataRow row in tblDatabases.Rows)
{
Console.WriteLine (“Database: ” + row[“database_name”]);
}
}

Regular expression for email

“^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$”

Get Laptop Battery Status using C#

To use this name space first of all we need to add reference to System.management by

Project Menu>>Add Reference.

after that at the top of the code use

 

using System.Management;

so that you can use of its classes . Now its simple to get information about laptop Battery through querying ManagementObjectSearcher Class .

We can get all information about Laptop Battery through Win32_Battery class.

so we need to query on that class to get related Management object and then we just need to get various properties related to it .

setup interface like below on the form

here i have taken two labels one textbox with read only property and one progress bar and a timer control .

now to get battery status we need to code like below .

 

Dictionary<UInt16, string> StatusCodes;

private void Form1_Load(object sender, EventArgs e)

{

StatusCodes = new Dictionary<ushort, string>();

StatusCodes.Add(1, “The battery is discharging”);

StatusCodes.Add(2, “The system has access to AC so no battery is being discharged. However, the battery is not necessarily charging”);

StatusCodes.Add(3, “Fully Charged”);

StatusCodes.Add(4, “Low”);

StatusCodes.Add(5, “Critical”);

StatusCodes.Add(6, “Charging”);

StatusCodes.Add(7, “Charging and High”);

StatusCodes.Add(8, “Charging and Low”);

StatusCodes.Add(9, “Undefined”);

StatusCodes.Add(10,”Partially Charged”);

 

/* Set progress bar values and Properties */

progressBar1.Maximum = 100;

progressBar1.Style = ProgressBarStyle.Continuous;

 

 

timer1.Enabled = true;

 

ManagementObjectSearcher mos = new ManagementObjectSearcher(“select * from Win32_Battery”);

foreach (ManagementObject mo in mos.Get())

{

lblBatteryName.Text = mo[“Name”].ToString();

UInt16 statuscode = (UInt16)mo[“BatteryStatus”];

string statusString = StatusCodes[statuscode];

lblBatteryStatus.Text = statusString;

}

}

 

private void timer1_Tick(object sender, EventArgs e)

{

ManagementObjectSearcher mos = new ManagementObjectSearcher(“select * from Win32_Battery where Name='”+lblBatteryName.Text+”‘”);

foreach (ManagementObject mo in mos.Get())

{

 

UInt16 statuscode = (UInt16)mo[“BatteryStatus”];

string statusString = StatusCodes[statuscode];

lblBatteryStatus.Text = statusString;

 

/* Set Progress bar according to status  */

if (statuscode == 4)

{

progressBar1.ForeColor = Color.Red;

progressBar1.Value = 5;

}

else if (statuscode == 3)

{

progressBar1.ForeColor = Color.Blue;

progressBar1.Value = 100;

}

else if (statuscode == 2)

{

progressBar1.ForeColor = Color.Green;

progressBar1.Value = 100;

}

else if (statuscode == 5)

{

progressBar1.ForeColor = Color.Red;

progressBar1.Value = 1;

}

else if (statuscode == 6)

{

progressBar1.ForeColor = Color.Blue;

progressBar1.Value = 100;

}

}

}

 

Here i have used few status only to show in progress bar you can code whatever you want to show in progress bar..

 

File Transfer Program using C#.Net Windows Application


How to easily send files (including Audio, Video, doc or any type of file) from Client to Server.

It is necessary to specify the server’s “Computer Name” in the TcpClient space like:

TcpClient client = new TcpClient(“SwtRascal”, 5055);

In this the TcpClient specified the Computer Name as “SwtRascal”.

And place an OpenFileDialog from the ToolBox-> Dialogs-> OpenFileDialog control.

Then Double-Click the form; the coding page will open; in that specify the following namespaces:

using System.Net.Sockets;
using System.IO;

Then write code for the button1 (Browse) and the button2 (Send) as in the following.

For example:

CLIENT PROGRAM:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;

namespace filee
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string n;
byte[] b1;
OpenFileDialog op;

private void button1_Click(object sender, EventArgs e)
{
op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
{
string t = textBox1.Text;
t = op.FileName;
FileInfo fi = new FileInfo(textBox1.Text = op.FileName);
n = fi.Name + “.” + fi.Length;
TcpClient client = new TcpClient(“SwtRascal”, 5055);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(n);
sw.Flush();
label1.Text = “File Transferred….”;
}

}

private void button2_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient(“SwtRascal”, 5050);
Stream s = client.GetStream();
b1 = File.ReadAllBytes(op.FileName);
s.Write(b1, 0, b1.Length);
client.Close();
label1.Text = “File Transferred….”;

}
}
}

For Server : Open a new C# Windows Application form.

Create and design a Form for Server like:

Then Place a folderBrowserDialog from the ToolBox->Dialogs-> folderBrowserDialog.

After Designing the Form, Double-Click the form; the coding page will open; in that specify the following namespaces:

using System.Net.Sockets;
using System.IO;
using System.Net;

Then write code for the button1 (Browse) and for the Form Load function, such as in the following.

If you want to specipy an IP Address for the system then include code such as:

Instead of using the code TcpListener list = new TcpListener(port1);

It only specifies the port address.

Use this code.

It specifies the IP Address and Port.

IPAddress localAddr = IPAddress.Parse(“192.168.1.20”);
TcpListener list = new TcpListener(localAddr, port);

For example:

SERVER PROGRAM:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Net;

namespace filee
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
string rd;
byte[] b1;
string v;
int m;
TcpListener list;

Int32 port = 5050;
Int32 port1 = 5055;
//IPAddress localAddr = IPAddress.Parse(“192.168.1.20”);

private void Browse_Click(object sender, EventArgs e)
{

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
//TcpListener list = new TcpListener(localAddr,port1);
list = new TcpListener(port1);
list.Start();
TcpClient client = list.AcceptTcpClient();
Stream s = client.GetStream();
b1 = new byte[m];
s.Read(b1, 0, b1.Length);
File.WriteAllBytes(textBox1.Text + “\\” + rd.Substring(0,            rd.LastIndexOf(‘.’)), b1);
list.Stop();
client.Close();
label1.Text = “File Received……”;
}

}

private void Form2_Load(object sender, EventArgs e)
{
//TcpListener list = new TcpListener(localAddr, port);
TcpListener list = new TcpListener(port);
list.Start();
TcpClient client = list.AcceptTcpClient();
MessageBox.Show(“Client trying to connect”);
StreamReader sr = new StreamReader(client.GetStream());
rd = sr.ReadLine();
v = rd.Substring(rd.LastIndexOf(‘.’) + 1);
m = int.Parse(v);
list.Stop();
client.Close();

}

}

}

After Designing the Forms for Client and Server, run the Server first and after that run the Client.


C# : Get system memory information

This example returns the usage of physical and virtual memory. You will need to add System.management as a reference.

using System;
using System.Management;

namespace MemInfo
{
class Program
{
static void Main(string[] args)
{
ObjectQuery winQuery = new ObjectQuery(“SELECT * FROM Win32_LogicalMemoryConfiguration”);

ManagementObjectSearcher searcher = new ManagementObjectSearcher(winQuery);

foreach (ManagementObject item in searcher.Get())
{
Console.WriteLine(“Total Space = ” + item[“TotalPageFileSpace”]);
Console.WriteLine(“Total Physical Memory = ” + item[“TotalPhysicalMemory”]);
Console.WriteLine(“Total Virtual Memory = ” + item[“TotalVirtualMemory”]);
Console.WriteLine(“Available Virtual Memory = ” + item[“AvailableVirtualMemory”]);
}
Console.Read();
}

Output:
——-

Total Space = 4033036
Total Physical Memory = 2095172
Total Virtual Memory = 1933904
Available Virtual Memory = 116280

Compressing and DeCompressing a File in C#

Methods to compress file and decompress file using System.IO.Compression

Method to compress a file.

public
void CompressFile ( string sourceFile, string destinationFile )

{

// Check File exists in the source path

if ( File.Exists ( sourceFile ) == false )

throw new FileNotFoundException ( );

// Create the streams and byte arrays

byte[] buffer = null;

FileStream sourceStream = null;

FileStream destinationStream = null;

GZipStream compressedStream = null;

try

{

// Read the bytes from the source file into a byte array

sourceStream =
new FileStream ( sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read );

// Read the source stream values into the buffer

buffer =
new byte[sourceStream.Length];

int checkCounter = sourceStream.Read ( buffer, 0, buffer.Length );

if ( checkCounter != buffer.Length )

{

throw new ApplicationException ( );

}

// Open the FileStream to write

destinationStream =
new FileStream ( destinationFile, FileMode.OpenOrCreate, FileAccess.Write );

// Create a compression stream pointing to the destiantion stream

compressedStream =
new GZipStream ( destinationStream, CompressionMode.Compress, true );

// Now write the compressed data to the destination file

compressedStream.Write ( buffer, 0, buffer.Length );

}

catch ( ApplicationException ex )

{

MessageBox.Show ( ex.Message, “Error occured during compression”, MessageBoxButtons.OK, MessageBoxIcon.Error );

}

finally

{

// Close all streams

if ( sourceStream != null )

sourceStream.Close ( );

if ( compressedStream != null )

compressedStream.Close ( );

if ( destinationStream != null )

destinationStream.Close ( );

}

}

Method to DeCompress a file.

public
void DecompressFile ( string sourceFile, string destinationFile )

{

// Check File exists in the source path

if ( File.Exists ( sourceFile ) == false )

throw new FileNotFoundException ( );

// Create the streams and byte arrays needed

FileStream sourceStream = null;

FileStream destinationStream = null;

GZipStream decompressedStream = null;

byte[] quartetBuffer = null;

try

{

// Read in the compressed source stream

sourceStream =
new FileStream ( sourceFile, FileMode.Open );

// Create a compression stream pointing to the destiantion stream

decompressedStream =
new GZipStream ( sourceStream, CompressionMode.Decompress, true );

// Read the footer to determine the length of the destiantion file

quartetBuffer =
new byte[4];

int position = (int)sourceStream.Length – 4;

sourceStream.Position = position;

sourceStream.Read ( quartetBuffer, 0, 4 );

sourceStream.Position = 0;

int checkLength = BitConverter.ToInt32 ( quartetBuffer, 0 );

byte[] buffer = new byte[checkLength + 100];

int offset = 0;

int total = 0;

// Read the compressed data into the buffer

while ( true )

{

int bytesRead = decompressedStream.Read ( buffer, offset, 100 );

if ( bytesRead == 0 )

break;

offset += bytesRead;

total += bytesRead;

}

// Now write to the destination file

destinationStream =
new FileStream ( destinationFile, FileMode.Create );

destinationStream.Write ( buffer, 0, total );

// Flush to clean out the buffer

destinationStream.Flush ( );

}

catch ( ApplicationException ex )

{

MessageBox.Show ( ex.Message, “An Error occured during compression”, MessageBoxButtons.OK, MessageBoxIcon.Error );

}

finally

{

// Close all streams

if ( sourceStream != null )

sourceStream.Close ( );

if ( decompressedStream != null )

decompressedStream.Close ( );

if ( destinationStream != null )

destinationStream.Close ( );

}

}