Tuesday, 29 April 2014

C#.NET - How to delete XML Node from XML file step by step

In this article you will get to know how to delete an Xml Node from the Xml Document.

We have an XmlDocument class in System.Xml namespace. With the help of XmlDocument class data members and member functions we can delete node from the Xml Document.

To delete an Xml node from the Xml Document go through the following step by step procedure.

1. First create an Xml File with some sample employees as follows.


Xml File

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  
  <Employee>
    <ID>SE01</ID>
    <Name>Srinubabu</Name>
    <Address>Hyderabad</Address>   
  </Employee>

  <Employee>
    <ID>SE02</ID>
    <Name>Gajendra</Name>
    <Address>Pune</Address>
  </Employee>

  <Employee>
    <ID>SE03</ID>
    <Name>Prafulla</Name>
    <Address>Gurgon</Address>
  </Employee>

  <Employee>
    <ID>SE02</ID>
    <Name>Satheesh</Name>
    <Address>Chennai</Address>
  </Employee>
  
</Employees>

2. Create a new website in Visual Studio.

3. Add an aspx page "Delete-node-from-xml.aspx" to the website and write the following code.

Note: Please go through the code and comments in the following code you will easily understand the process of deleting the node from Xml Document.



Delete-node-from-xml.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Delete-node-from-xml.aspx.cs"
    Inherits="Delete_node_from_xml" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <form id="form1" runat="server">
    Employee ID:
    <asp:TextBox ID="txtEmployeeID" runat="server" />
    <asp:Button ID="btnDeleteEmployee" Text="Delete Employee" runat="server" OnClick="btnDeleteEmployee_Click" /><br />
    <br />
    <asp:Label ID="lblStatus" ForeColor="Red" Font-Size="13" Text="" runat="server" />
    </form>
</body>
</html>

Delete-node-from-xml.aspx.cs

using System;
using System.Xml;

public partial class Delete_node_from_xml : System.Web.UI.Page
{
   
    protected void btnDeleteEmployee_Click(object sender, EventArgs e)
    {
        var filePath = @"C:\Users\manduvalkuritis\Desktop\Srinubabu\XMLManipulations\Employees.xml";
        DeleteEmployeeByEmployeeID(filePath, txtEmployeeID.Text.Trim());
    }

    private void DeleteEmployeeByEmployeeID(string xmlFilePath, string employeeID)
    {
        // Initialize a new instance of the XmlDocument.
        var xdoc = new XmlDocument();
        xdoc.Load(xmlFilePath);

        // Get the root XmlElement of the document.
        XmlNode rootNode = xdoc.DocumentElement;

        // Select a list of Xml nodes matching with employee ID
        XmlNodeList nodes = rootNode.SelectNodes("Employee");

        bool isEmployeeFound = false;

        // Go throug each and every element 
        foreach (XmlNode item in nodes)
        {
            // Find the Xml node with the given employee ID
            if (item.SelectSingleNode("ID").InnerText == employeeID)
            {
                isEmployeeFound = true;

                // Delete the employee node from the xml document.;
                rootNode.RemoveChild(item);
            }
        }

        if (isEmployeeFound)
        {
            lblStatus.Text = "Emloyee Deleted Successfully.";
        }
        else
        {
            lblStatus.Text = "Emloyee doesn't found please enter correct employee id.";
        }

        // Finally save the xml file.
        xdoc.Save(xmlFilePath);
    }
}


4. Now run the page in browser the output of the page looks as follows.



5. Enter an invalid employee id which was not available in Xml Document and then click on delete button. It will show the error message as follows.



6. Now enter a valid employee id and click on delete button. Now an employee node will be delete from the xml document.



7. Now open the Xml file and observe an employee node with the id "". The employee node with the employee id "" deleted from the Xml file.


Xml File

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  
  <Employee>
    <ID>SE02</ID>
    <Name>Gajendra</Name>
    <Address>Pune</Address>
  </Employee>
  
  <Employee>
    <ID>SE03</ID>
    <Name>Prafulla</Name>
    <Address>Gurgon</Address>
  </Employee>
  
  <Employee>
    <ID>SE02</ID>
    <Name>Satheesh</Name>
    <Address>Chennai</Address>
  </Employee>
  
</Employees>

So, In this way we can delete a node from the Xml Document.

Thank you....

Monday, 7 April 2014

C#.NET - Programming code to generate pyramid or triangle with '*' character

Today you will learn how to generate a pyramid or triangle with characters. Generally you may get this type of requirement in interview to test your coding skills.

Here I created one class in Console Application. Save this as a *.cs file and run it within your Console Application.


C# code to generate pyramid with characters

using System;
using System.Text;

class PrintPyramid
{
    static void Main()
    {
        // Ask for the number to generate pyramid.
        Console.Write("Please enter number to generate triangle: ");
        // Get the input value.
        var noOfRows = Convert.ToInt64(Console.ReadLine());

        // Generate pyramid with the given value.
        GenerateTriangle(noOfRows, '*');

        // Wait for the response from command line.
        Console.ReadLine();
    }

    // Method to generate pyramid
    private static void GenerateTriangle(long noOfRows, char charForTriangle)
    {
        // Create an instance of type StringBuilder to store spaces.
        var sbSpaces = new StringBuilder();

        // Add Spaces to the StringBuilder.
        for (int spaces = 1; spaces < noOfRows; spaces++)
        {
            sbSpaces.Append(" ");
        }

        // Take initial row value as 1.
        var noPrint = 1;
        for (long number = 1; number <= noOfRows; number++)
        {
            // Print spaces first.
            Console.Write(sbSpaces);

            // Print 'X' in a single line to generate proper pyramid.
            for (long i = 1; i <= noPrint; i++)
            {
                Console.Write(charForTriangle);
            }

            // After printing one line come to second line.
            Console.WriteLine();

            // Increment noPrint value to add more 'X' to line.
            noPrint += 2;

            // Each time remove one space from StringBuilder to generate pyramid.
            if (sbSpaces.Length > 0)
                sbSpaces.Remove(0, 1);
        }
    }
}

Output:
















Friday, 4 April 2014

C#.NET Program to generate Prime Numbers

Prime number:
A number which is greater than 1 and divisible by 1 or itself is called prime number.
2 is an even prime number because it is evenly divisible by itself and divisible by 1.
All even numbers are not prime numbers. If the last digit of the number contains 0 2 4 6 8 then the number divisible by 2 thus the number is not a prime number.

Ex: First few prime numbers are 2, 3, 5, 7, 11, 13 ..........

Here I am posting a code snippet how to generate Prime Numbers.

C# Prime Numbers Generator

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class PrimeNumbers
    {
        static void Main()
        {
            Console.Write("Please enter a number to generate prime numbers: ");

            var ipVal = Convert.ToInt64(Console.ReadLine());

            var primeNumbers = GetPrimeNumbersUpTo(ipVal);

            PrintPrimeNumbers(primeNumbers, ipVal);

            Console.ReadLine();
        }

        private static void PrintPrimeNumbers(List<long> primeNumbers, long range)
        {
            Console.WriteLine();
            Console.WriteLine("Prime numbers between 2 to " + range);
            foreach (long item in primeNumbers)
            {
                Console.WriteLine(item);
            }
        }

        private static List<long> GetPrimeNumbersUpTo(long ipVal)
        {
            var primeList = new List<long>();
            for (long value = 2; value <= ipVal; value++)
            {
                if (IsPrimeNumber(value))
                {
                    primeList.Add(value);
                }
            }
            return primeList;
        }

        private static bool IsPrimeNumber(long inputValue)
        {
            if (inputValue == 0 || inputValue == 1)
            {
                return false;
            }

            if (inputValue == 2)
            {
                return true;
            }

            var roundedVal = (long)Math.Round(Math.Sqrt(inputValue));

            for (long i = 2; i <= roundedVal; i++)
            {
                if (inputValue % i == 0)
                {
                    return false;
                }
            }
            return true;
        }
    }
}

Output:







C#.NET program to check whether a given number is prime number or not.

Prime number:
A number which is greater than 1 and divisible by 1 or itself is called prime number.
2 is an even prime number because it is evenly divisible by itself and divisible by 1.
All even numbers are not prime numbers. If the last digit of the number contains 0 2 4 6 8 then the number divisible by 2 thus the number is not a prime number.

Ex: First few prime numbers are 2, 3, 5, 7, 11, 13 ..........

Here I am posting a code snippet to find whether a given number is prime number or not.


C# Program For Prime Number

using System;

namespace ConsoleApplication1
{

    class Program
    {
        static void Main()
        {
            Console.Write("Please enter number to check prime or not: ");
            long inputValue = Convert.ToInt32(Console.ReadLine());

            if (IsPrimeNumber(inputValue))
            {
                Console.WriteLine(inputValue + " is prime number");
            }
            else
            {
                Console.WriteLine(inputValue + " is not prime number");
            }

            Console.ReadLine();
        }

        private static bool IsPrimeNumber(long inputValue)
        {
            if (inputValue == 0 ||inputValue == 1)
            {
                return false;
            }

            if (inputValue == 2)
            {
                return true;
            }

            var roundedVal = (long)Math.Round(Math.Sqrt(inputValue));

            for (long i = 2; i <= roundedVal; i++)
            {
                if (inputValue % i == 0)
                {
                    return false;
                }
            }
            return true;
        }

    }
}

Output:

















Thursday, 3 April 2014

C#.NET, ASP.NET - Generate non repeated random numbers in C#.NET within the range with the help of Random class.

Hi All,
In this article I will show you how to generate a non repeated random number in between specified range step by step with the explination of code in C#.NET with the help of ASP.NET page.

First please have a look at the complete script page and code behind file.


Generate-Random-Number.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Generate-Random-Number.aspx.cs" Inherits="Scripts_MAR_RandomNumber" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        table tr td:first-child
        {
            width: 45px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        Enter Number: 
        <table class="auto-style1">
            <tr>
                <td>From:</td>
                <td>
                    <asp:TextBox ID="txtFrom" MaxLength="4" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>To:</td>
                <td>
                    <asp:TextBox ID="txtTo" MaxLength="4" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="btnGenerate_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblStatus" runat="server" ForeColor="Red" Text=""></asp:Label>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:TextBox ID="txtRandomNumbers" TextMode="MultiLine" runat="server" Height="113px" Width="434px"></asp:TextBox>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Generate-Random-Number.aspx.cs

using System;
using System.Collections.Generic;
using System.Text;

public partial class Scripts_MAR_RandomNumber : System.Web.UI.Page
{
    
    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        // Check the From and To fields have a valid numeric numbers.
        if (IsValidForm())
        {
            // Generate Random Numbers.
            var randomNumers = GenerateRandomNumbers(Convert.ToInt32(txtFrom.Text), Convert.ToInt32(txtTo.Text));

            // Write random numbers to TextBox.
            PrintRandomNumbers(randomNumers);
        }
    }

    // Method to write non repeated random numbers to the TextBox.
    private void PrintRandomNumbers(List<int> randomNumers)
    {
        // Create a StringBuilder to hold the random numbers.
        var sbNumbers = new StringBuilder();
        foreach (var number in randomNumers)
        {
            // Add random numbers from List to StringBuilder.
            sbNumbers.Append(number + ", ");
        }

        // Write random numbers from StringBuilder to TextBox
        txtRandomNumbers.Text = sbNumbers.ToString();
    }

    // Method to generate non repeat random numbers.
    private List<int> GenerateRandomNumbers(int minValue, int maxValue)
    {
        // Create an instance of Random class.
        var randGenerator = new Random();

        // Create an instance of List<int> to store random numbers.
        var randValues = new List<int>();

        int randNum = 0;

        for (int value = minValue; value <= maxValue; value++)
        {
            // Generate a new random number between range (Min, Max). 
            randNum = randGenerator.Next(minValue, maxValue + 1);

            // Check if the new generated random number is existed in List.
            while (randValues.Contains(randNum))
            {
                // If the the number exists generate new random number with in the range (Min, Max).
                randNum = randGenerator.Next(minValue, maxValue + 1);
            }

            // Add non repeated random number to the List
            randValues.Add(randNum);
        }

        // Return non repeated random numbers List.
        return randValues;
    }

    // Method to check the values are entered in the From field and To field are numeric are not.
    private bool IsValidForm()
    {
        var validForm = true;
        int value = 0;

        // Check From value is empty or not.
        if (string.IsNullOrWhiteSpace(txtFrom.Text))
        {
            validForm = false;
            lblStatus.Text = "Please enter From value.";
        }
        else
            // Check From value is integer or not.
            if (!int.TryParse(txtFrom.Text, out value))
            {
                validForm = false;
                lblStatus.Text = "Please enter valid numeric value in From field.";
            }
            else
                // Check From value is negative or not.
                if (Convert.ToInt32(txtFrom.Text) < 0)
                {
                    validForm = false;
                    lblStatus.Text = "Please enter positive value in From field.";
                }
        // If the value entered in From field is valid then check for To value.
        if (validForm)
        {
            // Check To value is empty or not.
            if (string.IsNullOrWhiteSpace(txtTo.Text))
            {
                validForm = false;
                lblStatus.Text = "Please enter To value.";
            }
            else
                // Check To value is integer or not
                if (!int.TryParse(txtTo.Text, out value))
                {
                    validForm = false;
                    lblStatus.Text = "Please enter valid numeric value in To field.";
                }
                else
                    // Check To value is negative or not
                    if (Convert.ToInt32(txtTo.Text) < 0)
                    {
                        validForm = false;
                        lblStatus.Text = "Please enter positive value in To field.";
                    }
        }
        // If both From and To fields are integers then check for "From value < To value"
        if (validForm)
        {
            if (Convert.ToInt32(txtFrom.Text) >= Convert.ToInt32(txtTo.Text))
            {
                validForm = false;
                lblStatus.Text = "From value should be less than To value.";
            }
        }
        if (validForm)
        {
            if (Convert.ToInt32(txtTo.Text) < Convert.ToInt32(txtFrom.Text))
            {
                validForm = false;
                lblStatus.Text = "To value should be greater than From value.";
            }
        }

        // Return the form is valid or invalid.
        return validForm;
    }
}


Step By Step Explanation:

1. Create an interface with two TextBoxes and one Button as shown in the Script page.

2. In the Button click event write the following code.
protected void btnGenerate_Click(object sender, EventArgs e)
    {
        // Check the From and To fields have a valid numeric numbers.
        if (IsValidForm())
        {
            // Generate Random Numbers.
            var randomNumers = GenerateRandomNumbers(Convert.ToInt32(txtFrom.Text), Convert.ToInt32(txtTo.Text));

            // Write random numbers to TextBox.
            PrintRandomNumbers(randomNumers);
        }
    }
The above Button click code is using 3 different methods to process different actions.

3. Write a method IsValidForm() to check the form fields are satisfying the following conditions. -  Check From value is empty or not.
-  Check From value is integer or not.
-  Check From value is negative or not.
-  If the value entered in From field is valid then check for To value.
-  Check To value is empty or not.
-  Check To value is negative or not
-  If both From and To fields are integers then check for "From value < To value"
-  Return the form is valid or invalid.

// Method to check the values are entered in the From field and To field are numeric are not.
    private bool IsValidForm()
    {
        var validForm = true;
        int value = 0;

        // Check From value is empty or not.
        if (string.IsNullOrWhiteSpace(txtFrom.Text))
        {
            validForm = false;
            lblStatus.Text = "Please enter From value.";
        }
        else
            // Check From value is integer or not.
            if (!int.TryParse(txtFrom.Text, out value))
            {
                validForm = false;
                lblStatus.Text = "Please enter valid numeric value in From field.";
            }
            else
                // Check From value is negative or not.
                if (Convert.ToInt32(txtFrom.Text) < 0)
                {
                    validForm = false;
                    lblStatus.Text = "Please enter positive value in From field.";
                }
        // If the value entered in From field is valid then check for To value.
        if (validForm)
        {
            // Check To value is empty or not.
            if (string.IsNullOrWhiteSpace(txtTo.Text))
            {
                validForm = false;
                lblStatus.Text = "Please enter To value.";
            }
            else
                // Check To value is integer or not
                if (!int.TryParse(txtTo.Text, out value))
                {
                    validForm = false;
                    lblStatus.Text = "Please enter valid numeric value in To field.";
                }
                else
                    // Check To value is negative or not
                    if (Convert.ToInt32(txtTo.Text) < 0)
                    {
                        validForm = false;
                        lblStatus.Text = "Please enter positive value in To field.";
                    }
        }
        // If both From and To fields are integers then check for "From value < To value"
        if (validForm)
        {
            if (Convert.ToInt32(txtFrom.Text) >= Convert.ToInt32(txtTo.Text))
            {
                validForm = false;
                lblStatus.Text = "From value should be less than To value.";
            }
        }
        if (validForm)
        {
            if (Convert.ToInt32(txtTo.Text) < Convert.ToInt32(txtFrom.Text))
            {
                validForm = false;
                lblStatus.Text = "To value should be greater than From value.";
            }
        }

        // Return the form is valid or invalid.
        return validForm;
    }
4. Write a method GenerateRandomNumbers(int minValue, int maxValue) to generate the non repeated random numbers with the following the steps.
- Create an instance of Random class.
- Create an instance of List<int> to store random numbers.
- Generate a new random number between range (Min, Max). 
- Check if the new generated random number is existed in List.
- If the the number exists generate new random number with in the range (Min, Max).
- Add non repeated random number to the List
- Return non repeated random numbers List.

// Method to generate non repeat random numbers.
    private List<int> GenerateRandomNumbers(int minValue, int maxValue)
    {
        // Create an instance of Random class.
        var randGenerator = new Random();

        // Create an instance of List<int> to store random numbers.
        var randValues = new List<int>();

        int randNum = 0;

        for (int value = minValue; value <= maxValue; value++)
        {
            // Generate a new random number between range (Min, Max). 
            randNum = randGenerator.Next(minValue, maxValue + 1);

            // Check if the new generated random number is existed in List.
            while (randValues.Contains(randNum))
            {
                // If the the number exists generate new random number with in the range (Min, Max).
                randNum = randGenerator.Next(minValue, maxValue + 1);
            }

            // Add non repeated random number to the List
            randValues.Add(randNum);
        }

        // Return non repeated random numbers List.
        return randValues;
    }
5. Write a method  PrintRandomNumbers(List<int> randomNumers) to print the values in TextBox.
- Create a StringBuilder to hold the random numbers.
- Add random numbers from List to StringBuilder.
- Write random numbers from StringBuilder to TextBox

// Method to write non repeated random numbers to the TextBox.
    private void PrintRandomNumbers(List<int> randomNumers)
    {
        // Create a StringBuilder to hold the random numbers.
        var sbNumbers = new StringBuilder();
        foreach (var number in randomNumers)
        {
            // Add random numbers from List to StringBuilder.
            sbNumbers.Append(number + ", ");
        }

        // Write random numbers from StringBuilder to TextBox
        txtRandomNumbers.Text = sbNumbers.ToString();
    }
6. Run the page and test the page by giving the following values in From field and To field.
From: 1
To: 10
From: 1
To: 100

Output: 


C#.NET - Object Oriented Programming interview questions with answers - Part 3

Hi All, I researched on .NET and collected important interview questions on C#.NET Object Oriented Programming. 
I am posting interview questions with answers parts by parts.


Please Find Other Interview Questions

C#.NET - Object Oriented Programming interview questions with answers - Part 2

C#.NET - Object Oriented Programming interview questions with answers - Part 1


Note: To initialize a static class or a static fields you must create a static constructor.
Note: It is better to make data members as private because if you make them as public anyone can access it from outside. So, protect data members by making them as private and initialize them through the properties and make properties as public.
What is a default constructor?
A constructor which is not have any arguments.
Note: If your class doesn't have any default constructor. a default constructor will automatically generates and assign default values to the data members.
Note: All C# types including premitive types such as int and double, inherit from a sigle base Object type.
Note: Assemblies contains the executable code in the form of IL code, and symbolic information in the form of metadata.
What is the default access level of constructor?
private
Note: Generally private constructors used in the classes that contains the static members only. Like Math class. Match class have static members and methods.
Note: We can use a private constructor to initialize the static members of the class.
Can you inherit the class which is have the private constructor?
No, you cannot.
In which type of situations we use private constructors?
If you want to prevent the user from instantiating the class we can use private constructor.
In which situtation you will use static constructor?
Generally in the situation when you want to initialize the static data of the class.
Explain about destructor?
Destructor is used to released the instances of the class.
Structs doesnt support the destructors.
A class should have only one destructor.
Destructor will call automatically by the garbage collector.
Destructor cannot be overloaded and inherited.
Destructor doesn't have modifiers as well as parameters.
Destructor internally call the Finalize() method.
What Object initializers do?
Object initializers allows us to access the fields and properties of the class at the time of the object creation. Instead of declaring the parametarised constructor in the class to assign the values to the fields and properties we can use the Object initializers.
Note: While you initializing data to the members of the class using object initilizers compiler will call the default constructor of the class.
So, If a class have the private default constructor object initializers will give the compile time error.
What is a Nested Type?
A type wich is declared under the class or the struct.
By default nested types are private.
You can get all the parent type members inside the nested type.
You can create the object of the nested type as follows.
Parent.Nested obj=new Parent.Nested();
Note: Partial method declaration must starts with the contextual keyword and must return the void.
Partial methods cannot be virtual.
Partial methods can be static.
Explain Anonymous Types?
Anonymous types are introduced in C# 3.0.
These are the datatypes generated at runtime by the compiler.
These are helpful in LINQ queries.
EX:
var employees=from employee in Employees
select new {employee.Name, employee.Salary}
Instead of selecting the whole properties of the employee we can select few of them.
Note: Value types donnot allow inheritance
Note: ?? operator used to compare with nullable types.
Note: Static methods cannot be inherited or oveerriden.
Explain about partial method?
Partials methods are defined their signature in once partial type and implemented in another partial type.
If partial method has no implementation the compiler will remove the partial method from the class at compile time.

Paritial methods are always private.
Partial methods must return void.
In both signature and implemtation signature should match.
Assume two interfaces have one method with same name and return type.

interface IInterface1
{
void Method1();
}
interface IInterface2
{
void Method1();
}
you are inheriting those two interfaces into one class.

class Program:IInterface1,IInterface2
{
}
How can you implement those methods in your derived class and how can you call the respected methods of interfaces?
interface IInterface1
{
void Method1();
}
interface IInterface2
{
void Method1();
}
class Program:IInterface1,IInterface2
{
static void Main()
{
IInterface1 aa = new Program();
aa.Method1();
IInterface2 aa2 = new Program();
aa2.Method1();
}

void IInterface1.Method1()
{
Console.WriteLine("Methods of IInterface1");
}
void IInterface2.Method1()
{
Console.WriteLine("Methods of IInterface2");
}
}

// Output
// Methods of IInterface1
// Methods of IInterface2
What is encapsulation?
Wrapping up of a data into a single unit (i.e. class) is called encapsulation.

It is a technique to hide the internal members of a class.

We can hide the private information and we can show the public information using encapsulation.
EX: hiding the properties and exposing the property to access the private data.

Wednesday, 2 April 2014

ASP.NET, C#.NET - How to download a file in ASP.NET using C#.NET?

Hi All,
By using the following simple code snippet page you can download any type of file in ASP.NET using C#.NET.
Please observe the steps in the following code to know how the 'file downloading process' is happening.


FileManagement.aspx

<%@ Page Language="C#" %>
 
<!DOCTYPE html>
 
<script runat="server">
 
    protected void Page_Load(object sender, EventArgs e)
    {
        var fullFilePath = @"D:\Krish\gallery (1).jpg";
        DownloadFile(fullFilePath, System.IO.Path.GetFileName(fullFilePath));
    }  
    
    private void DownloadFile(string fullFilePhysicalPath, string downloadbleFileName)
    {
 
        // Create New instance of FileInfo
        System.IO.FileInfo file = new System.IO.FileInfo(fullFilePhysicalPath);
 
        // Checking if file exists
        if (file.Exists)
        {
            // Clear the content of the response
            Response.ClearContent();
 
            // Add the file name and attachment
            Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadbleFileName);
 
            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());
 
            // Set the ContentType
            Response.ContentType = GetFileExtension(file.Extension.ToLower());
 
            // Write the file into the response 
            // ASP.NET 2.0 - TransmitFile
            // ASP.NET 1.1 - WriteFile
            Response.TransmitFile(file.FullName);
 
            // End the response
            Response.End();          
        }
    }
 
    private string GetFileExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>