How to clear temporary internet foder by using C# in winforms?

Here is the sample code for clearing temporary internet foder by using C# in winforms.

private void btnClear_Click(object sender, EventArgs e)
ClearAll(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)));
MessageBox.Show("Your temporary files has been cleaned.! ");

public void ClearAll(DirectoryInfo dirInfo)
foreach (FileInfo fileInfo in dirInfo.GetFiles())
catch { }
foreach (DirectoryInfo subDirectory in dirInfo.GetDirectories())


How to insert bulk values in to a table by using C#?

The below method is used to bulk insert in to a table by using c# from a datatable.

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

public int BulkInsert(DataTable dt, string TableName, string ConnectionString)
int returnValue = -1;
SqlConnection oConn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM " + TableName,oConn);
da.SelectCommand.Connection = oConn;
DataSet ds = new DataSet();
SqlCommandBuilder oCmd = new SqlCommandBuilder(da);
returnValue = da.Update(dt);
catch (Exception ex)
throw ex;
return returnValue;


Copy All Directories with Files using C#

Here is the sample code for copying a directory with sub directories and all the files using C#.

public static void CopyAllDirectories(DirectoryInfo source, DirectoryInfo target)
if (Directory.Exists(target.FullName) == false)

foreach (FileInfo fileInfo in source.GetFiles())
{ fileInfo.CopyTo(Path.Combine(target.ToString(),fileInfo.Name), true);
foreach (DirectoryInfo sourceSubDir in source.GetDirectories())
DirectoryInfo targetSubDir =
CopyAllDirectories (sourceSubDir, targetSubDir);


Scrollbar in down side of textbox.

Scrollbar in down side of textbox.

Hi all, I have come to give a very simple solution for the below question. The question is

How to set scrollbar in end of the text in textbox when dynamically updating the text value?

Actually I have been developing a big application. On that application I needed to update the status of every action in my application. For the purpose of updating the status, I have used the textbox to show the status with multiline and vertical scrollbar properties. But I could see the vertical bar not going down when updating the status as shown in the below figure which is marked in red.

After googling few minutes I found we have some properties and methods in textboxes of visual studio are SelectionStart and ScrollToCaret method.

By using the above property and method I have found the solution for my question. See the below figure...

Code Snippet:

private void btnUpdate_Click(object sender, EventArgs e)
if (!string.IsNullOrEmpty(txtStatus.Text))
txtStatus.Text = txtStatus.Text + Environment.NewLine;
txtStatus.Text = txtStatus.Text + "Status Updated...";

txtStatus.SelectionStart = txtStatus.Text.Length;


Barcode Generation using C#

In this article, I am trying to give you a sample code for generating barcode image by using C#.

We can see in market for all products they are using barcode only. So the barcode is common one. When we try to programming with old language for barcode is very difficult. We needed to go third party component. But in .Net framework it is very easy to generate barcode image.

Barcode font

There is lot of free barcode fonts available in internet. We can search and download it for generating the barcode image. Here is the font which is I am using “Barcodefont.ttf”. We need to download this font and install in your fonts folder which is located in control panel.

For generating barcode image, we need to add the namespaces “System.Drawing, System.Drawing.Imaging” and the file management namespaces.

Sample Code

using System.Drawing.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

public string dirPath = "";

dirPath = Environment.CurrentDirectory;

private void GenerateBarCode()
string path = dirPath + "\\" + DateTime.Now.ToFileTimeUtc().ToString() + ".jpg";
PrivateFontCollection fontCollection = new PrivateFontCollection();
fontCollection.AddFontFile(dirPath + "\\BarcodeFont.ttf");
FontFamily fontFamily = new FontFamily("barcode font", fontCollection);
Font font = new Font(fontFamily, 40);

Bitmap bmp = new Bitmap(pbBarcodeImage.Width, pbBarcodeImage.Height);
Graphics graphics = Graphics.FromImage(bmp);
SizeF sizeF = graphics.MeasureString(txtEnter.Text.Trim(), font);
Brush brush = new SolidBrush(Color.Black);
graphics.DrawString(txtEnter.Text.Trim(), font, brush, 10, 10);
bmp.Save(path, ImageFormat.Jpeg);
pbBarcodeImage.Image = new Bitmap(path);
{ }

Hence we are generating the barcode by using the above code.


Inserting Bulk Data in SQL Server from Text file

There is a simple query to do this bulk insert in to sql server from a text file. The thing is that we have to keep a fully formatted text file with appropriate data’s which are to be inserted.

Here, we have a table to be inserted is,

The query for creating table,

FName varchar (100) NOT NULL,
LName varchar (100) NOT NULL,
Email varchar (100) NOT NULL

Then we have a text file with the bulk data’s like as follows,


Now the query for inserting bulk data is,

BULK INSERT Employee FROM 'c:\bulktext.txt' WITH (FIELDTERMINATOR = ',')

Now you can see the data's inserted in table by the select query as follows,

select * from Employee

The following image is being explained the above matters.


Multiple Colored texts in RichTextBox using C#

This article is created for making multiple colored texts in a textbox. By using the SelectionText property in richtextbox we have created a sample application for multiple colored texts in Microsoft’s richtextbox control. Let us see how to make it in below code.

Font font = new Font("Tahoma", 8, FontStyle.Regular);
richTextBox1.SelectionFont = font;
richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectedText = Environment.NewLine + textBox1.Text;

By using the above code, we can make a multiple colored texts in our richtextbox. This is basically used for doing some chat application. We will have to show the other end of person’s text in different color in chat application. So that we can use this method. And we can create a simple method and calling in every time of showing the text in richtextbox with the parameters of like “textbox1.text, color,..etc”.

For more visit my article in codeproject here with more explanation.


How to sum previous rows value SqlServer?

I needed to write a query for sum the values with the previous row value in current row of a column. So that I have written a single query after a long googled. Here I am trying to give you what I have done.

I have a table with three fields Id, Name and Mark. I have values of all fields like as follows.

Id Name Mark
--- ----- -----

1 aaaa 10
2 bbbb 20
3 cccc 30

Now I wants to get the results set of that table like as

Id Name Mark
--- ----- -----

1 aaaa 10
2 bbbb 30

3 cccc 60

So I need a single select query to do this performance. For that I have written a query using cross join.

Code Snippets for Table and Query

CREATE TABLE [dbo].[Marks]( [Id] [bigint] NOT NULL, [Name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Mark] [bigint] NOT NULL ) ON [PRIMARY]

select * from Marks

select a.Id, a.Name, sum(b.Mark) as Mark
from Marks a cross join Marks b
where b.Id <= a.Id group by a.Id, a.Name

Hence we have done the fetching the result set for sum of the previous rows in sql server.

For more ...

visit here


Multiple rows in a single row with separator in SqlServer

Here is a simple way to make a single row value from multiple rows with a separator in SqlServer.

I have a table like the following…

Table Name: People

select * from people

Now I need the ‘Name’ column values where matching the value of ‘aaaa’ in to a single row. For this I have tried to make a query.

Just use the following query to get the solution.

declare @res varchar(1000)
select @res = coalesce(@res + ',', '') +Name
from people
WHERE Name = 'aaaa'

select @res

See the result…


Simple recursive function for string folding in C#

Here is the sample function of string folding in c#. I just tried bind the body content of a mail in to a label box. For that I need to folding the string content. I have created a method to do this string folding as follows,

if (lblBody.Text.Length > 150)
lblBody.Text = lblbodystring(lblBody.Text,150);

//Simple recursive function for string folding.
private string lblbodystring(string bodyString, int Length)
string retVal = "";
if (bodyString.Length > Length)
retVal = bodyString.Substring(0, Length);
retVal = retVal + Environment.NewLine;
retVal = retVal + lblbodystring(bodyString.Substring(Length));
retVal = retVal + Environment.NewLine;
retVal = retVal + bodyString;
return retVal;

The thing is that we can use textbox with multiline attribute for this kind of process :). But I have used in label. So...


Query for importing data’s from XL to SqlServer DB

Here is a simple query for importing data's from Microsoft Excel sheet to Sql Server database.

Just copy the following code and run in your sql server query window. Before that make XL sheet with the appropriate fields and values and place it in c drive or wherever you wants.

INSERT INTO [dbo].[TableName] ([FieldName1] ,[FieldName2] ,[FieldName3] ,[FieldName4] FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'Data Source=C:\db.xls;Extended Properties=Excel 8.0')...[SheetName$]

that's it...


Silverlight - Introduction

Microsoft Silverlight is a programmable web browser plug-in that enables features such as animation, vector graphics and audio-video playback that characterizes rich Internet applications.

Silverlight provides a retained mode graphics system similar to Windows Presentation Foundation, and integrates multimedia, graphics, animations and interactivity into a single runtime environment. In Silverlight applications, user interfaces are declared in XAML and programmed using a subset of the .NET Framework. XAML can be used for marking up the vector graphics and animations. Textual content created with Silverlight is searchable and indexable by search engines as it is not compiled, but represented as text (XAML).


1. Silverlight 1.0
2. Silverlight 2
3. Silverlight 3

Tools for Silverlight application

To developing Silverlight application, Microsoft has been released some set of tools. They are,

• Visual Studio 2008 with Service Pack 1
• Silverlight 2 Beta 2 SDK
• Expression Blend 2 July 2008 Preview

All of us known about Visual Studio. Expression Blend is Microsoft's user interface design tool for creating graphical interfaces for web and desktop applications. Blend is writing using the .NET Framework 3.0 and Windows Presentation Foundation (WPF). Microsoft Expression Blend does the same of Adobe Photoshop to edit your images as well as add effects to existing images.

How to create Silverlight applications?

There is a question in our mind raising that “How to create Silverlight applications?” Here is the answer for your question,

1. Use Visual Studio 2008 SP1 to create a new Silverlight project based on the Silverlight 2 Beta 2 Template. Visual Studio will do the necessary steps to add a single HTML page or a single website to host your Silverlight application. This is because Silverlight is a plug-in that renders in the browser.

2. Add your necessary XAML files needed for the user interface. This is similar to the forms that you would add to a Windows Form application.

3. Edit the XAML page using Expression Blend 2 July 2008 preview. Note that Because each page in Silverlight 2 Beta 2 is treated as a user control, only Expression Blend 2 July 2008 preview will be capable of opening these particular XAML files. Any older version of Expression Blend will throw an error message saying that it is unable to open that file type.

4. Switch to Visual Studio 2008 SP1 to write code behind files for the controls and pages that you created in Step 2.

5. Build and compile the application.

6. Host the same in IIS or any web server of your choice. For this demonstration, you will rely on Windows Vista for development and IIS for hosting the application.


Simple Collapse Panel - Windows application in C#

Hi all, There is no option to collapsing functionality in panel control.

I have created a panel control with up/down arrow images. We can collapse this control by clicking those arrows. There are some property values allowing us the interval of collapsing time. The ScrollInterval value is used to set the interval time for collapsing animation. And the HeaderHeight property value is set to be the height of header part in this control. I just used some calculation to set the height value for this control in a certain loop. This much of calculation makes some animation to collapsing the control.

You can see the magic of this control by downloading the demo project which is available to download here.

The simple calculation of control’s height is possible to collapse the control. Just see the following code,

if (this.Height > this.lblTop.Height)
while (this.Height > this.lblTop.Height)
this.Height -= ScrollIntervalValue;
this.lblTop.ImageIndex = 1;
this.Height = this.lblTop.Height;
else if (this.Height == this.lblTop.Height)
int x = this.FixedHeight;
while (this.Height <= (x))
this.Height += ScrollIntervalValue;
this.lblTop.ImageIndex = 0;
this.Height = x;

Just refer the control in your application, and add the control in your form. Then set the property values of this control ScrollInterval and HeaderHeight as you want. If you don’t set those property values it might be taken by default values. Now build your project and run. By clicking the arrow images in collapse panel, you can see the magic.

For More…see my article in code project.


How do we change the header BackColor and selected color in ListView using c#?

How do we change the header BackColor and selected color in ListView using c#?

Yes, we can make it possible to change the header backcolor and style for ListView control. And also we can change the some styles in ListView control in the code behind. Here is the way to explain how it is possible.

There is property named “OwnerDraw” is used to do the style changing process by our code behind. Just we need to set that property as “true”.

I have a ListView control with the name of “lstView” in my sample form, and the code has been written as follows,

this.lstView.BackColor = System.Drawing.SystemColors.ControlText;
this.lstView.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lstView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.lstView.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.lstView.FullRowSelect = true;
this.lstView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lstView.Location = new System.Drawing.Point(2, 1);
this.lstView.MultiSelect = false;
this.lstView.Name = "lstView";
this.lstView.OwnerDraw = true;
this.lstView.View = System.Windows.Forms.View.Details;

private void lstView_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
System.Drawing.Drawing2D.LinearGradientBrush GradientBrush = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, Color.Blue, Color.LightBlue, 270);

e.Graphics.FillRectangle(GradientBrush, e.Bounds);

e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.White), 2), e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 2, e.Bounds.Height - 2);

e.Graphics.DrawString(e.Header.Text, new Font("Arial", 12), new SolidBrush(Color.Yellow), e.Bounds);

private void lstView_DrawItem(object sender, DrawListViewItemEventArgs e)
if (e.Item.Selected)
e.Graphics.FillRectangle(new SolidBrush(Color.DarkBlue), e.Bounds);
e.Graphics.DrawString(e.Item.Text, new Font("Arial", 10), new SolidBrush(Color.White), e.Bounds);

private void lstView_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
e.Graphics.DrawString(e.Item.Text, new Font("Arial", 10), new SolidBrush(Color.White), e.Bounds);

That's it...


How to change the header backcolor in datagridview C#

Here I am trying to get the new design for my DataGridView header back color. So that, I have been tried a lot in Google and got the solution which is explained below.

Set the following properties for your DataGridView control by using the properties window.

EnableHeadersVisualStyles = False

RowHeadersBorderStyle = Raised

Then copy the following code in your Form_Load event.

DataGridViewCellStyle style = this.dataGridView1.ColumnHeadersDefaultCellStyle;
style.BackColor = Color.WhiteSmoke;
style.ForeColor = Color.Gray;
style.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

Now run your application, the header style would be changed and showing a new style that we wants.


What is OfType operator in LINQ?

OfType operator in LINQ

OfType operator is used to return objects of a certain type. For example if we have an array of objects which contains strings, decimal, float and numbers or any other. We can use OfType operator to extract only strings or any particular type of values.

Here is an example to fetch the string values from an array of objects. See below,

private void Form1_Load(object sender, EventArgs e)
object[] values = {"test1",45,'c',"test2",34.67,12/12/2009,"test3",4.0,4.4f};
var strings = values.OfType();
int top = 10;
foreach (var s in strings)
Label lbl = new Label();
lbl.Top = top;
top = top + 30;
lbl.Text = s;

You just copy the above code in to Form_Load and run the solution. There will be shown the string values.


How to disable the Win Form’s Close Button ?

Disable the Win Form’s Close Button using C#

Here is the simple way to disable the Form’s close button. Just copy the following code in your code behind. Then run the form, surely the close button would be disabled.

private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams
CreateParams myCp = base.CreateParams;
myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
return myCp;

That's it...


Differences between XBAP, WPF Standalone and Silverlight

Differences between XBAP, WPF Standalone and Silverlight

WPF applications are divided into two categories.

• Standalone WPF Application
• XAML browser applications (XBAPs)

There is always a confusion between WPF, XBAP and Silverlight. Developers get confused which one to go for while designing a project. Here I will explain all the 3 technologies with the differences

Standalone WPF Application

- WPF applications are installed on end user's machine.

- Appear in Start Menu and Add/Remove Programs.

- Applications can be installed via MSI or ClickOnce.

- User can be offline and use the application. There is no need for Internet connection.

- Newer versions of the application may not be automatically installed in user's machine.

- WPF standalone applications can use WCF for communication.

- Applications run in its own window as other windows applications.

XAML Browser Application(XBAP)

- These type of applications are not installed in user's machine.

- They do not appear in the in Start Menu or Add/Remove Programs.

- Applications can be automatically deployed via ClickOnce.

- Applications are hosted in the browser process.

- Can be run only in IE and Firefox.

- Newer versions are always installed automatically into the user's machine.

- User must be online to use the application.

- XBAP is Windows only. We can run the application in Windows operating system only.

- XBAPs cannot use WCF.

- The user machine should have .NET framework 3.0 components.


- XBAP is IE and Firefox only. But Silverlight can run in any browser and platform.

- Silverlight is used for creating rich UI web application.

- User's machine don't need .NET framework.

- Can be embedded in HTML markup and rendered in any browser using the silverlight plug in.

- XABP has 99% features of WPF. But Silverlight is just a subset of WPF.


XBAP - Windows Presentation Foundation XAML Browser Applications

XBAP - Windows Presentation Foundation XAML Browser Applications

XBAP – XAML Browser Application is a new windows technology used for creating Rich Internet Applications. It is used for creating heavyweight .Net applications.

XAML Browser Applications combines features of both Web applications and rich-client applications. While windows applications are normally compiled to an .exe file, browser applications are compiled to an extension .xbap and can be run inside Internet Explorer.

Like Web applications, XBAPs can be published to a Web server and launched from Internet Explorer. Like rich-client applications, XBAPs can take advantage of the capabilities of WPF. Developing XBAPs is also similar to rich-client development.

Implementing a XAML Browser Application (XBAP)

The simplest way to create a new XBAP project is with Microsoft Visual Studio:

1. On the File menu, point to New, and then click Project.
2. In the New Project dialog box, in the Project types pane, choose either Visual Basic or Visual
C#. In the Templates pane, click WPF Browser Application.
3. Assign a project name and click OK to create the new project.

The WPF Browser Application project template creates an XBAP application project that includes the following:

• An application definition, Application.xaml.
• A page, Page1.xaml.

You can add to those as required.

If you prefer developing with tools that require command-line compilation.

When you run an XBAP, it is launched in a browser window instead of a standalone window. When you debug an XBAP from Visual Studio, the application runs with Internet zone permission and will consequently throw security exceptions if those permissions are exceeded.

Deploying a XAML Browser Application

When you build a XBAP, the Microsoft build engine (MSBuild) produces the following three files as a minimum:

• An executable file. This contains the compiled code and has an .exe extension.
• An application manifest. This contains metadata associated with the application and has a
.manifest extension.
• A deployment manifest. This file contains the information that ClickOnce uses to deploy the
application and has an .xbap extension.

You publish XBAPs to a Web server (Microsoft Internet Information Services (IIS) or later). You do not need to install .NET Framework on the Web server, but you do need to register the WPF Multipurpose Internet Mail Extensions (MIME) types and file extensions.

To prepare your XBAP for deployment, copy the .exe and the associated manifests to your Web server. Create a hyperlink on a Web page to navigate to the deployment manifest. When the user clicks the link and navigates to the .xbap file, ClickOnce automatically handles the mechanics of downloading and launching the application.




How to create Vista Gadget

We can create a Vista Sidebar Gadget by easily. Just follow the below steps then you are the owner of a sidebar gadget.

Step 1:

Create the following html file with the name of “HelloWorld.html”.

Step 2:

Create the following xml file with the name of “Gadget.xml”.

Step 3:

Create a folder called Helloworld.Gadget

Step 4:

1.Simply copy”%userprofile%\AppData\Local\Microsoft\Windows Sidebar\Gadgets” and paste in Windows explorer address bar.
2. When you get to that folder Copy and Paste the “HelloWorld.Gadget” folder there.

Step 5:

Add the gadget to your Sidebar and your done !

For more visit here …


How to get duration of an audio file in c# ?

We can get the duration of an audio or video file by using the “Shell32” namespace in Visual Studio Dot Net. For that we need to add the reference of “Interop.Shell32.dll” in to our project. And follow the given method in below. By calling the following method with the parameter of full path of file name which might be an audio file or video file we can get the duration of that file.

private string GetDuration(string FileFullPath)
string duration = "";
string fName = FileFullPath.Substring(FileFullPath.LastIndexOf("\\") + 1);
string filePath = FileFullPath.Substring(0, FileFullPath.LastIndexOf("\\"));
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(filePath);
Shell32.FolderItem folderItem = folder.ParseName(fName);
if (folderItem != null)
duration = folder.GetDetailsOf(folderItem, 21);
folderItem = null;
folder = null;
shell = null;
return duration;

Hence we can get the duration of given file.


Find Age from given DateOfBirth using C#

Hi all,

Just copy the following method in your class and call it with the parameters of date of birth and current date in DateTime format.

public string FindAge(DateTime dob, DateTime currentDate)
int years = currentDate.Year - dob.Year;
int months = 0;
int days = 0;
if(currentDate < dob.AddYears(Years) && Years != 0)
dob = dob.AddYears(years);
if (dob.Year == currentDate.Year)
months = currentDate.Month - dob.Month;
months = (12 - dob.Month) + currentDate.Month;
if(currentDate < dob.AddMonths(months) && months != 0)
dob = dob.AddMonths(months);
days = (currentDate - dob).Days;
return years + " years " + months + " months " + days + " days";

Copy the above code in your class...and call the method..enjoy... ;)


Code for moving the form by mouse clicking.

Hi Viewers,

Here by I am trying to give you a sample code for moving the win form by clicking the mouse.

Just use the following code and test it.

using System.Runtime.InteropServices;

public const int WM_NCLBUTTONDOWN = 0xA1;

public const int HT_CAPTION = 0x2;

public static extern int SendMessage(IntPtr hWnd,int Msg, int wParam, int lParam);

public static extern bool ReleaseCapture();

private void Form1_MouseDown(object sender, MouseEventArgs e)
if (e.Button == MouseButtons.Left)

Now you can implement the above code in your application and test it. Working fine for me


Add prerequisites of dotnet framework in visual studio setup project

When we developing an application using any platform we should prepare our application to be deployed properly. Specially for dotnet, the prerequisites of dotnet framework is must. So here by I am explaining how to add framework to be installed before our application installation process.

After developing our .Net application we need to create a setup project. Just follow the steps mentioned in below.

- Go to File menu, select Add New Project and then select Setup And Deployment in under “Other Project Types”.

- Give a name to your project as your wish.

- Then select your setup project solution and add Primary output of your developed project. You just need to right click your setup project in solution explorer, click add --> Project Output --> select your project.

- Then add custom action by right clicking setup project --> view --> Custom Actions --> right click Custom Actions --> Add Custom Actions.

- Now we are going to add the prerequisites for your setup project.

- Select your setup project right click and go to properties then click the Prerequisites button.

- Now select .Net Framework 2.0 tick box after selecting the “Create setup program to install prerequisite components”.

- Then specify the install location for prerequisites by selecting the option box.

- Here I am selecting the second one “Download prerequisites from the same location as my application”.

- Click ok and apply then ok.

- Now build your setup project, the dotnet framework will be added in your debug folder.

That's it...


FileSystemWatcher in C#

Hi all,

Here is the simple description to use FileSystemWatcher in your desktop application by using C#.

Just drag the FileSystemWatcher control in your form from under the Components tab in the toolbox.

And copy the following code in to load event,

private void Form1_Load(object sender, EventArgs e)
fileSystemWatcher.Path = flvPath;
fileSystemWatcher.Filter = "*.flv";
fileSystemWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.LastWrite;
fileSystemWatcher.EnableRaisingEvents = true;

If the file watcher found any newly created file, the following event will rise.

private void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
MessageBox.Show(e.Name + " created in " + e.FullPath);

An event is rising when a file deleted.

private void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
MessageBox.Show(e.Name + " changed in " + e.FullPath);

An event is rising when a file renamed.

private void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
MessageBox.Show(e.Name + " renamed in " + e.FullPath);

That’s it…


How to generate an xml from TreeView using C#?

Hi guys,

Here is the sample code for generating xml file from TreeView. I needed this for one of my project. I just referred lot of sites and finally came to conclusion with the following code. Just copy and paste this code and use it for yours.

using System.IO;

private static StreamWriter sr;

private void btnExportXML_Click(object sender, EventArgs e)
if (tvXML.Nodes.Count > 0) // Here tvXML is TreeView control
sr = new StreamWriter(path); // Here path is xml path
sr.Write("<" + tvXML.Nodes[0].Text + ">");

//Use the following method for getting value of each and every node

private static void parseNode(TreeNode tn)
IEnumerator ie = tn.Nodes.GetEnumerator();
string parentnode = "";
parentnode = tn.Text;
while (ie.MoveNext())
TreeNode ctn = (TreeNode)ie.Current;
if (ctn.GetNodeCount(true) == 0)
if (ctn.Tag != null)
sr.Write("<" + ctn.Text + ">");
sr.Write("<" + ctn.Text + "/>");
sr.Write("<" + ctn.Text + ">");
if (ctn.GetNodeCount(true) > 0)


How to bind Countries in a combobox using c#?

Find the code below to bind countries in a combo box using C#.

public void BindCountries()
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures))
RegionInfo ri = new RegionInfo(ci.LCID);
comboBox1.Sorted = true;
comboBox1.SelectedIndex = 0;


Using ClientScriptManager in C#

We know that we all are using the script tag for JavaScript function in our web page. In the case of some situations we need to add the scripts in code behind by dynamically. So .Net Framework 2.0 introduced a class namely “ClientScriptManager” that is used to manage script in code behind.

Now we are going to about the ClientScriptManager class and its usage with some sample codes.


This class is used to manage client scripts in .Net. We can get the object of this class from Page.ClientScript. We need to register the client script by using the method of RegisterClientScriptBlock () which is from that object of ClientScriptManager.

The ClientScriptManager class uniquely identifies scripts by a key String and a Type. Scripts with the same key and type are considered duplicates. Using the script type helps to avoid confusing similar scripts from different user controls that might be in use on the page.

The ClientScriptManager class can be used to invoke client callbacks in situations when it is desirable to run server code from the client without performing a postback. This is referred to as performing an out-of-band callback to the server. In a client callback, a client script function sends an asynchronous request to an ASP.NET Web page. The Web page runs a modified version of its normal life cycle to process the callback. Use the GetCallbackEventReference method to obtain a reference to a client function that, when invoked, initiates a client callback to a server event.

(This is from MSDN)

Let we watch this in Code behind. Just use the following code in page load and run it.

1. RegisterClientScriptBlock()

In Page_Load,

protected void Page_Load(object sender, EventArgs e)
//Get the ClientScript property as an object of ClientScriptManager from Page object.
ClientScriptManager client = this.Page.ClientScript;
//Check the script block is not already registered
if (!client.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
client.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('Welcome !')", true);

2. RegisterStartupScript()

RegisterClientScriptBlock and RegisterStartupScript both the methods are using to fire during the startup of page. But the difference is that the RegisterClientScriptBlock method will fire the script “after the form open tag but before the page controls”. And the RegisterStartupScript method will fire the script “after page controls but before the form close tag”. So the first method won’t get the controls value in run time.

For example, we are having a label box with the text “Vinoth” in a form, and then call the script as follows,

ClientScriptManager client = this.Page.ClientScript;
if (!client.IsStartupScriptRegistered(this.GetType(), "Alert"))
client.RegisterStartupScript(this.GetType(), "Alert", "alert(document.getElementById('lblName.Text'))", true);


How do I change the color of the title bar in a Win Forms .Net app using c#?

We can use the WM_NCPAINT Message to do that. We must have to code for override the WndProc method to change the color of title bar in a Win Forms. Here I have done that with the following code. You can do that by using the code below.

using System.Runtime.InteropServices;

static extern int ReleaseDC(IntPtr hWnd, IntPtr hDc);

private static extern IntPtr GetWindowDC(IntPtr hWnd);

protected override void WndProc(ref Message m)
base.WndProc(ref m);
const int WM_NCPAINT = 0x85;
if (m.Msg == WM_NCPAINT)
IntPtr hdc = GetWindowDC(m.HWnd);
if ((int)hdc != 0)
Graphics g = Graphics.FromHdc(hdc);
g.FillRectangle(Brushes.Green,new Rectangle(0,0,300,22));
ReleaseDC(m.HWnd, hdc);

That’s it…


Creating a database with filestream using (C#) SMO in DotNet 3.5.

The following code will help you to do the creating database with filestream.

Here am using the SMO from Visual Studio Dot Net 3.5. Smo object is very useful to do the sqlserver manipulations from code end. However we could create a db with filestream. Just go thru the following code and use it.

using Microsoft.SqlServer.Management.Smo;

string dbName = "DBName";
string dbServerMachineName = "MachineName";

string mdfFile = mdfDirectory+@"\" + dbName + ".mdf";
string ldfFile = ldfDirectory + @"\" + dbName + "_log.ldf";
string FilesDir = FilesDirectory +@"\" + dbName;

Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(dbServerMachineName);

Database database = new Database(server, dbName);
//Adding Primary FileGroup
database.FileGroups.Add(new FileGroup(database, "PRIMARY"));
//Adding FileStream FileGroup
database.FileGroups.Add(new FileGroup(database, "FileStreamTest", true));
//Adding Files for Primary FileGroup
DataFile dtPrimary = new DataFile(database.FileGroups["PRIMARY"], "PriValue", mdfFile);
dtPrimary.Size = 77.0 * 1024.0;
dtPrimary.GrowthType = FileGrowthType.KB;
dtPrimary.Growth = 1.0 * 1024.0;
//Adding Files for FileStream FileGroup
database.FileGroups["FileStreamTest "].Files.Add(new DataFile(database.FileGroups["FileStreamTest "], " FileStreamTest Values", FilesDir));
//Adding LogFile
LogFile logFile = new LogFile(database, "PriValue_log", ldfFile);
logFile.Size = 7.0 * 1024.0;
logFile.GrowthType = FileGrowthType.Percent;
logFile.Growth = 10.0;
//Create database.


How to restore a DataBase from .bak file using (C#) SMO in DotNet 3.5?

The following code will help you to do this restore processing.

using Microsoft.SqlServer.Management.Smo;

string backupFile="Backupfile";//.bak file

string dbName = "DBName";

string dbServerMachineName = "MachineName";

Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(dbServerMachineName);

Database database = new Database(server, dbName);

//If Need




Restore restore = new Restore();

restore.NoRecovery = false;

restore.Action = RestoreActionType.Database;

BackupDeviceItem bdi = default(BackupDeviceItem);

bdi = new BackupDeviceItem(backupFile, DeviceType.File);


restore.Database = dbName;

restore.ReplaceDatabase = true;

restore.PercentCompleteNotification = 10;






How to taking backup a database using (c#) DotNet framework 3.5? Or using SMO?

How to taking backup a database using (c#) DotNet framework 3.5? Or using SMO?

Add the following reference in your project for using SMO through “Add Reference”.

- Microsoft.SqlServer.ConnectionInfo

- Microsoft.SqlServer.Management.Sdk.Sfc

- Microsoft.SqlServer.Smo

- Microsoft.SqlServer.SmoExtended

- Microsoft.SqlServer.SqlEnum

Now, you can use the following code for taking backup of given database using SMO.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using Microsoft.SqlServer.Management.Smo;

string MachineName="Your MachineName";

string DBName="Your DBName";

string backupName = "tempBackup";

Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(MachineName);

Database db = server.Databases[DBName];

//To Avoid TimeOut Exception

server.ConnectionContext.StatementTimeout = 60 * 60;

RecoveryModel recoverymodel = db.DatabaseOptions.RecoveryModel;

//Define a Backup object variable.

Backup backup = new Backup();

backup.CompressionOption = BackupCompressionOptions.On;

//Specify the type of backup, the description, the name, and the database to be backed up.

backup.Action = BackupActionType.Database;

backup.BackupSetDescription = "Full backup of " + DBName + ".";

backup.BackupSetName = backupName;

backup.Database = DBName;

//Declare a BackupDeviceItem

BackupDeviceItem bdi = default(BackupDeviceItem);

bdi = new BackupDeviceItem(@"C:\ " + backupName + ".bak", DeviceType.File);

//Add the device to the Backup object.


//Set the Incremental property to False to specify that this is a full database backup.

backup.Incremental = false;

//Set the expiration date.

System.DateTime backupdate = new System.DateTime();

backupdate = new System.DateTime(2008, 10, 5);

backup.ExpirationDate = backupdate;

//Specify that the log must be truncated after the backup is complete.

backup.LogTruncation = BackupTruncateLogType.Truncate;

//Run SqlBackup to perform the full database backup on the instance of SQL Server.


//Remove the backup device from the Backup object.


That's it...