Wednesday, May 21, 2008

How to Write & Read from Windows Registry using C#?

So we need to store our settings!

Since writing to INI files is kind of out dated, writing settings to the windows registry seems to be good enough. (its not new, even windows 3.1 had it... and the whole reg thing seems to be getting out dated too... lets forget about that and assume its good for the moment.)


So How to write & read from Windows Registry using C#?

I can straight away give you the code... but that doesn't seem to be not quite satisfying.

For those who are not familiar with Windows Registry, i'd give a simple briefing here.


Windows registry is the hive of logical information where windows OS it self and other applications keep their settings/configuration/etc data stored.


CAUTION: Making un-necessary changes to the existing registry items may cause malfunctioning of Windows OS or other applications. So beware!


Windows registry is designed in a hierarchical structure, with keys, sub keys and different types of values stored inside keys.

Following screenshot is an illustrated view of windows registry, that will give u a basic idea.




[click on image to see in full size]
What you see there is the windows built in registry editor (regedit.exe) u can use it to manually edit/view registry.

Windows registry is separated into several sections catering several purposes.

Sections/hives are as follows:

HKEY_CLASSES_ROOT (HKCR) - stores information about reged applications; file associations, OLE Object Class IDs.
HKEY_CURRENT_USER (HKCU) - stores settings specific to the currently logged-in user.
HKEY_LOCAL_MACHINE (HKLM)- stores settings that are general to all users on the computer. Contains four subkeys, SAM, SECURITY, SOFTWARE and SYSTEM. Subkey, HARDWARE, is volatile and is created dynamically.
HKEY_USERS (HKU) - contains subkeys corresponding to the HKEY_CURRENT_USER keys for each user profile actively loaded on the machine
HKEY_CURRENT_CONFIG - contains information gathered at runtime, compiled at boot; information stored in this key is not permanently stored.
HKEY_PERFORMANCE_DATA - provides runtime information into performance data provided by either the NT kernel itself or other programs that provide performance data. This key is not displayed in the Registry Editor, but it is visible through the registry functions in the Windows API.

So now you can decide where u gonna store your reg values.

Then lets get into business! Here goes the code:
(These code snippets uses, "Microsoft.Win32" namespace.)

Writing a Key to Registry
=========================
///
/// Method to write a key & values to windows registry
///

private void writeReg()
{
// definition of registry key - keylevel node
// notice that here we are creating key in "CurrentUser"... u can alter this to suite your needs.
RegistryKey myKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\TestKey\\TestSubKey");
// check whether the key already exists
if (myKey == null)
{
MessageBox.Show("Null Masterkey!");
}
// if not
else
{
try
{
// set sample values
myKey.SetValue("MyKey", "MyValue1");
myKey.SetValue("xKey", "xValue-bhooo");
MessageBox.Show("Keys set!");
}
catch (Exception ex)
{
// ops!!
MessageBox.Show(ex.Message);
}
finally
{
// close RegistryKey
myKey.Close();
}
}
}


Reading a value from Registry
=============================
///
/// Method to read a value from windows registry
///

private void readRed()
{
string myregstring = "";
// open key
// notice that here our key is in "CurrentUser"... u can alter this to suite your needs.
RegistryKey myKey1 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\TestKey\\TestSubKey");
// if key does not exsists
if (myKey1 == null)
{
MessageBox.Show("Non exsisting key!");
}
// if key exsists
else
{
try
{ // get reg value into a string
myregstring = (string)myKey1.GetValue("xKey");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// close RegistryKey
myKey1.Close();
}
MessageBox.Show(myregstring);
}
}


Delete a key from Registry
==========================
///
/// Method to delete a key in windows registry
///

private void delKey()
{
// notice the overloaded OpenSubKey method now uses two arguments.
// second argument: bool writable - if true key will open in writeble mode.
RegistryKey myKey2 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\TestKey",true);
// if key does not exsists
if (myKey2 == null)
{
MessageBox.Show("Non exsisting key!");
}
// if key exsists
else
{
try
{
// delete the given key
myKey2.DeleteSubKey("TestSubKey");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// close RegistryKey
myKey2.Close();
}
}
}


Delete a key-tree from Registry
===============================
///
/// Method to delete a key and its tree (including sub-elements) in windows registry
///

private void delKeyTree()
{
// notice the overloaded OpenSubKey method now uses two arguments.
// second argument: bool writable - if true key will open in writeble mode.
RegistryKey myKey3 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\TestKey",true);
// if key does not exsists
if (myKey3 == null)
{
MessageBox.Show("Non exsisting key!");
}
// if key exsists
else
{
try
{
// delete the given key
myKey3.DeleteSubKeyTree("TestSubKey");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// close RegistryKey
myKey3.Close();
}
}
}


There are additional registry fuctions such as; count keys and count values which are not common in use and therefore not discusses here. See MSDN ;)

You can download a sample visual studio solution (C# project) that illustrate these codes from my website. [www.thekalana.net/downloads.html]

If you like to know more about windows registry, i'd recommend you to read: http://en.wikipedia.org/wiki/Windows_Registry

Tuesday, May 20, 2008

How to find IE proxy settings with Visual Studio C#?

In many cases of programming stuff that works with internet, it would be handy to know what are the proxy settings that Internet Explorer uses.

How to find proxy settings with Visual Studio C#? Here is the answer...

private static void CheckForProxy(Uri resource)

{

WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy();

Uri proxyUri = proxy.GetProxy(resource);

if (proxyUri == resource)

{

MessageBox.Show("No proxy for " + resource);

}

else

{

MessageBox.Show("Proxy for " + resource + " is " + proxyUri.ToString());

}

}

This code allows you to find out what proxy uses for each type of Uri.

Pass any server address for Uri parameter as a Uri object.

Example: ProxyCheck(new Uri("http://64.202.189.170"));

Note: This uses System.net namespace. Don't forget! :)

Saturday, May 17, 2008

FTP file upload with C#

Same as for ftp file download, To upload a file to a ftp server C# provides easy functionality with use of System.Net namespaces.

Following code is a method built upon that which uses FtpWebRequest to upload a file to a ftp server. We are using File streams as well and thats "using System.IO;".

You can download my sample visual studio solution (project) for FTP Uploads/Downloads at my web site [www.thekalana.net\downloads.html]

It is noticed that some proxy connections that allow ftp download not always allows ftp uploads. If you have trouble getting things working... check with that too.
Sample Source Code :

// Dont forget to add: using System.Net;

// SET THESE PARAMETERS FIRST

string ftpServerIP = "0.0.0.0"; // replace with your ftp server IP Address

string ftpUserID = "user"; // ftp server username

string ftpPassword = "password"; // ftp server password

///

/// Method for uploading a file to the specified FTP Server

///

/// - file name of local file

public void Upload(string filename)

{

FileInfo fileInf = new FileInfo(filename);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

FtpWebRequest reqFTP;

// Create FtpWebRequest object from the Uri

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

// Provide WebPermission Credintials

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

// By default KeepAlive is true, control connection is kept alive

reqFTP.KeepAlive = false;

// FTP Command to be executed.

reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// Data transfer type.

reqFTP.UseBinary = true;

// Notify the server - size of the uploaded file

reqFTP.ContentLength = fileInf.Length;

// Buffer size - 2kb

int buffLength = 2048;

byte[] buff = new byte[buffLength];

int contentLen;

// Open file stream (System.IO.FileStream) to read the file to be uploaded

FileStream fs = fileInf.OpenRead();

try

{

// Stream to which the file to be upload is written

Stream strm = reqFTP.GetRequestStream();

// Read from the file stream at above mentioned buffer size rate

contentLen = fs.Read(buff, 0, buffLength);

// till Stream content ends

while (contentLen != 0)

{

// Write Content from the file stream to the FTP Upload Stream

strm.Write(buff, 0, contentLen);

contentLen = fs.Read(buff, 0, buffLength);

}

// Close file stream

// Close Request Stream

strm.Close();

fs.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, "Upload Error");

}

}

Friday, May 16, 2008

FTP file download with C#

FTP file download with C# is a piece of cake as C# provides everything at our fingertips. As long as we have "using System.Net;" line at top... we are good.


Here we use FtpWEbRequest, FtpWebResponse (provided in System.Net namespace) and FileStream (System.IO) to get it done. I have done my best to provide as much as comments that would fit in a code! And the code is so simple so i should waste time writing an essay here... ;)


You can download my sample visual studio solution (c# project) for FTP Uploads/Downloads at my web site [www.thekalana.net\downloads.html]


Please note that; this code does not provide functionality to manipulate connecting via a proxy server. Still this will work with in Visual Studio since VS uses the proxy settings in IE. But u should explicitly use proxy manipulations in order to deploy the app. U can find code for capturing proxy settings from IE, in a proceeding post or at my web site [www.thekalana.net\downloads.html].


Sample Source Code :

///

/// Method for downloading a file to the specified FTP Server

///

public void Download(string localpath, string remotepath)

{

FtpWebRequest reqFTP;

try

{

//localpath = <>,

//remotepath = <>

//----- can use this block if neccesary to implement uploading with sub directory structure.

//string derivedpath = remotepath.Replace("/","_"); //remove all backslashes in remotepath and replace with underscore

//MessageBox.Show(derivedpath);

//-----

// Open file stream (System.IO.FileStream) to read the file to be downloaded

FileStream outputStream = new FileStream(localpath + "\\" + remotepath, FileMode.Create);

// Create FtpWebRequest object from the Uri

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + remotepath));

// FTP Command to be executed

reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;

// Data tranfer type

reqFTP.UseBinary = true;

// Provide WebPermission Credintials

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

Stream ftpStream = response.GetResponseStream();

long cl = response.ContentLength;

// Set buffer size

int bufferSize = 2048;

int readCount;

byte[] buffer = new byte[bufferSize];

// Read from the stream at above mentioned buffer size rate

readCount = ftpStream.Read(buffer, 0, bufferSize);

// till stream download ends

while (readCount > 0)

{

outputStream.Write(buffer, 0, readCount);

readCount = ftpStream.Read(buffer, 0, bufferSize);

}

// Close ftp stream

// Close file stream

// Close ftp response

ftpStream.Close();

outputStream.Close();

response.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

Saturday, May 3, 2008

iNFOPOP - Done!


well.. iNFOPOP... E-learning tool is finally done.

Nice!

Nice interface with 8 video preview panes (nice job Loli), support for nearly two dozens of various file formats, FTP uploads downloads and MSSQL backend database (danaa), multi user support for windows user profiles. AND... No design documents, no real database diagrams, oxford english user manual (mark! ;) ), some collected odd content (banda!)... what else....hmm.. its one hell of a good, lil-messed but a successful project.

After all that.. jus tot a few code snippets we used could possibly useful for someone.

So following stuff will be posted next;

- FTP File Upload with C#

- FTP File Download with C#

- Connecting, Reading data from a MSSQL database with C#

- Connecting, Writing data to a MSSQL database with C#

- Capturing proxy information from IE with C#

- Writing keys & values to windows registry with C#

Enjoy!