Sponsored Ad

Sunday, July 24, 2011

Publish and Deploy Code using Visual Studio

Visual studio provide very easy and good feature to publish ad deploy the code  and dlls. Follow the below steps to deploy and publish:

Step 1: Right click on project and select the publish option

Publish and Deploy Code using Visual Studio

Step 2: Select the Directory where you want to publish

There is 4 kind of location

  1. Disk Path
  2. File Share
  3. FTP Server
  4. Web site

Select as per your requirement.

Publish and Deploy Code using Visual Studio

Step 3: Select How user will install applcation

Publish and Deploy Code using Visual Studio

Step 4: Select option for application to check for updates.

Publish and Deploy Code using Visual Studio

Step 5: Click on Finish and publish the solution.

Publish and Deploy Code using Visual Studio

Search/Replace Text in Entire Solution by using Visual Studio Search

Visual studio provide different kind of search to find text in file(s) or selected File(s). The search available with VS are:

  1. Quick Find
  2. Quick Replace
  3. Find in files
  4. Replace in Files
  5. Find Symbols

You do any of the above search in visual studio.

To do the search in entire solution Go to Edit Menu –> Find and Replace –> Find in Files

Search/Replace Text in Entire Solution by using Visual Studio Search

Find in Files Search:

Search/Replace Text in Entire Solution by using Visual Studio Search 

Shortcut key to Find in Files : CTRL + SHIFT + F

How to Format Selected Source Code in Visual Studio Editor

Visual studio provide a very good functionality to format your source code automatically. If you code is not well formatted don't worry. just by a single click you can align all code. follow the below steps to do that.

Step 1: Go to Edit menu option

Step 2: Select Advanced and then select Format Document

Step 3: There is another option Format  Selection under Advanced , Please not that this is applicable for selected text only, so first select the option and then click on this option.

Shortcut keys for above functionality:

Format Document CTRL + E + D

Format  Selection CTRL + E + F

How to Format Selected Source Code in Visual Studio Editor

How to Change Font and Color of Visual Studio Editor

Visual studio provide a setting to change change font and color of text and other things available at editor. To change the look and feel follow the below steps:

Step 1: Click on Tools menu from visual studio IDE.

Step 2: Select Options from Tools menu.

Step 3: Select Environment and then select Fonts & Colors option

From the Fonts & Colors page you can change the font and color of different elements.

for example selected text, line number , book mark etc.

How to Change Font and Color of Visual Studio Editor

After changing the text color to red you can see that editor is showing normal text in red.

How to Change Font and Color of Visual Studio Editor

How to Edit Readonly File and Warn when Save in Visual Studio

Visual studio provide a option to allow editing of read only files. and if option is enable it will also display a message to override it. To enable disable read-only file option follow the below steps.

Step 1: Open Visual Studio – > Click On Tools menu

Step 2: Select Options

Step 3: Click on Environments  and then select Documents

Step 4: Under Documents page select/unselect “Allow editing of read-only files; warn when attempt to save” checkbox.

How to Edit Readonly File and Warn when Save in Visual Studio

Read only file save warning.

How to Edit Readonly File and Warn when Save in Visual Studio

Enable/Disable Visual Studio Notification When File is Changed from Outside

If a file which is already open in visual studio and is changed from outside of visual studio environment. The visual studio have a setting to tell you that file is changed and you want to reload this file or not.

if you click on yes it will reload the file otherwise will have old version of file.

Follow the below steps to enable/disable this setting.

Go to Tools –> Options –>  Environments –> Documents

and Enable disable Detect when file is changed outside the environment Checkbox.

Enable/Disable Visual Studio Notification When File is Changed from Outside

If you select the Auto-Load Changes if Saved , The visual studio will automatically reload the file.

Enable/Disable Visual Studio Notification When File is Changed from Outside

Saturday, July 23, 2011

Display/Show Toolbox in Visual Studio + Shortcut Key

To display Toolbox in Visual studio IDE, Follow the below steps:

Step 1. Go to View menu

Step 2: Click on Toolbox option,  the toolbox will appear in left hand side of visual studio.

Display/Show Toolbox in Visual Studio + Shortcut Key

There is keyboard shortcut  also to display toolbox

Press CTRL key + W + X from keyboard

How to Open/Display Solution Explorer in Visual Studio | Shortcut key

This post is to help, who are new to visual studio. If you closed the solution explorer from visual studio IDE. you can follow the following steps to display again:

Step 1: Go to View menu

Step 2: Click on Solution Explorer Option 

How to Open/Display Solution Explorer in Visual Studio | Shortcut key

Shortcut keys to open solution explorer:

Press  CTRL + W + S key to open solution explorer

Visual Studio Settings: How to Enable Word Wrap

The below steps will help you to enable word wrap in visual studio.

Step 1: Go Tools menu

Step 2: Click on Options

Step 3: Select The Text Editor and then select your language or All Language for All

Step 4: Select General and then go to settings option

Step 5: Select the Word Wrap option and click on save.

Tools –> Options –> Text Editor –> C# or All Language –> General –> Settings –> Check Word Wrap Option

How to Enable Word Wrap in Visual Studio Editor

Note : there is a option to show visual glips for word wrap, if you enable this you will get the visual indicator like below:

How to Enable Word Wrap in Visual Studio Editor

.NET Tips: Show Line number in Visual Studio Editor 2005/2008/2010

You can display line numbers in your visual studio editor. Just follow the following steps to display line numbers. by default line number are hidden.

Step 1: Go to Tools menu at the top of VS.

Step 2: Go to Options

Step 3: Go to Text Editor and then select C# or your language.

Step 4: Select Line number under display options.

Click on OK and it will display he line number in editor.

C# Tips: Display Line number in Visual Studio Editor 2008

Displaying line numbers in editor:

C# Tips: Display Line number in Visual Studio Editor 2008

Find Current Executing Assembly Name using C# Program

You can find out current executing assembly name by using the reflection. Reflection provide lot more details about the current executing assembly and you can read at runtime. The fully executing code is given below.

The below code is using GetExecutingAssembly() method to get the detail of current assembly.

Find Current Executing Assembly Name using C# Program

C# Example to Display Current Assembly Name:

using System;
using System.Data;

namespace DemoConsoleApplication

    class Get_Current_Assembly
    {
        static void Main(string[] args)
        {
            string str_Assembly_Name;
            str_Assembly_Name = System.Reflection.Assembly.GetExecutingAssembly().FullName;
            Console.WriteLine("Full Assembly Name: " + str_Assembly_Name);

            str_Assembly_Name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            Console.WriteLine("Only Assembly Name: " + str_Assembly_Name);

            Console.ReadLine();
        }
    }
}

Sample Program to Dispose Dataset by Using Block in C#

If you want to dispose dataset object after a certain operations. You can initialize dataset object inside the using block and the dataset object will automatically dispose once the block finish. Even the dataset object will not be available after the using block.

You can run the below code and check the this is one the good way to avoid the headache of disposing dataset.

Sample Program to Dispose Dataset by Using Block in C#

C# Example to create dataset object in using block:

using System;
using System.Data;

namespace DemoConsoleApplication
{
    class DataSet_Using_Block
    {
        static void Main(string[] args)
        {
            //Create a object of dataset in using block
            using (DataSet oDs = new DataSet("DemoDataset"))
            {
                Console.WriteLine("DataSet Created.");
                Console.WriteLine("DataSet Name inside using block:" + oDs.DataSetName);
            }

            try
            {
                //The below code will not compile as oDs is not visible.
               // Console.WriteLine("DataSet Name outside of using block:" + oDs.DataSetName);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Error Message: " + ex.Message );
            }

            Console.ReadLine();
        }
    }
}

What Dataset Namespace should be Included in C#

You can create a dataset object by including the System.Data namespace as dataset class is inside this namespace only.

The below program will help you to include the dataset namespace and also create a dataset object by specifying the name of dataset.

What Dataset Namespace should be used in C#

Sample program to create a dataset object and include the namespace:

using System;
using System.Data;

namespace DemoConsoleApplication
{
    class DataSet_NameSpace
    {
        static void Main(string[] args)
        {
            //Create a object of dataset
            DataSet oDs = new DataSet("TestDataset");
            Console.WriteLine("DataSet Created.");
            Console.WriteLine("DataSet Name:" + oDs.DataSetName);
            Console.ReadLine();
        }
    }
}

Tuesday, April 5, 2011

Inconsistent accessibility: property type 'MyApp.class_type' is less accessible than property 'MyApp.operator_error_class.my_prop' – C# Error

When you try to access a class from another class which have higher accessibility.

using System;

namespace MyApp
{
    public class Inconsistent_accessibility_Class
    {
        public static void Main(string[] args)
        {          
        }

        public class_type my_prop
        {
            get
            {
                return new class_type();
            }
        }

    }
    class class_type
    {
    }
}

How to fix above Error:

add public access in front of class_type class.

using System;

namespace MyApp
{
    public class Inconsistent_accessibility_Class
    {
        public static void Main(string[] args)
        {          
        }

        public class_type my_prop
        {
            get
            {
                return new class_type();
            }
        }

    }
    public class class_type
    {
    }
}

How to Fix C# Error: Operator '+' cannot be applied to operand of type 'string'

You will get this C# error (Operator '+' cannot be applied to operand of type 'string') when you try to apply binary + operator with only single operand. To fix this error, you need to have + operator between the two strings.

using System;

namespace MyApp
{
    class operator_error_class
    {
        public static void Main(string[] args)
        {

            string s = + "my string";
            Console.Read();
        }      
    }
}

Working version above program:

using System;

namespace MyApp
{
    class operator_error_class
    {
        public static void Main(string[] args)
        {

            string s = "Its" + "my string";
            Console.Read();
        }      
    }
}

How to Fix C# Error - Identifier too long

This error you will get when you try to declare a variable of length more than 512 chars. The below code will produce a compile time error: Identifier too long

using System;

namespace MyApp
{
    class too_long_class
    {
        public static void Main(string[] args)
        {
            int intsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss = 0;
            Console.WriteLine();
            Console.Read();
        }      
    }
}

To fix above error just reduce the number of char in variable name less than 512.

How to fix C# Warning - The variable 'i' is assigned but its value is never used

While coding i got a warning saying that “The variable 'i' is assigned but its value is never used”. This warning basically appear because the given variable is not in use.

If you compile the below code it will give above warning.

using System;

namespace MyApp
{
    class _class
    {
        public static void Main(string[] args)
        {
            int i = 0;
            Console.Read();
        }
    }
}

How fix above warning :

To fix above warning just use the unused variable anywhere in the code.

using System;

namespace MyApp
{
    class _class
    {
        public static void Main(string[] args)
        {
            int i = 0;
            Console.WriteLine(i);
            Console.Read();
        }
    }
}

Can we Initialize a Class Object with Object Class in C#

Someone asked me a question that can we initialize a class object with object class. No it is not possible because every class is derived from object class. So we can not assign object class object to any other class. While reverse is possible.

If you try to compile below program. It will give error saying:

Cannot implicitly convert type 'object' to 'MyApp._class.my_class'. An explicit conversion exists (are you missing a cast?)

using System;

namespace MyApp
{
    class _class
    {
        public static void Main(string[] args)
        {

            my_class cObj = new object();           

            Console.Read();
        }

        class my_class
        {
            public my_class()
            {
            }
        }
    }
}

Friday, April 1, 2011

Efficient way to convert Array to String using C#

Here is way to convert a given char array into string. Just pass the array into string constructor and it will automatically convert into string.

Efficient way to convert Array to String using C#

using System;

namespace MyApp
{
    class array_to_string_class
    {
        static void Main()
        {
            char[] array_var = new char[16];
            array_var[0] = 'S';
            array_var[1] = 'o';
            array_var[2] = 'f';
            array_var[3] = 't';
            array_var[4] = 'w';
            array_var[5] = 'a';
            array_var[6] = 'r';
            array_var[7] = 'e';
            array_var[8] = ' ';
            array_var[9] = 'T';
            array_var[10] = 'e';
            array_var[11] = 's';
            array_var[12] = 't';
            array_var[13] = 'i';
            array_var[14] = 'n';
            array_var[15] = 'g';

            string str = new string(array_var);
            Console.WriteLine(str);

            Console.Read();
        }
    }
}

Thursday, March 31, 2011

How to Handle Console Application Arguments using C#

How to Handle Console Application Arguments using C#

This program helps beginners to get the arguments passed on command line in C# program. you can read these arguments from main method.

How to Handle Console Application Arguments using C#

using System;

namespace MyApp
{
    class console_arguments_class
    {
       public static void Main(string[] my_args)
        {
            Console.WriteLine("Number of Arguments: " + my_args.Length);
            for (int i = 0; i < my_args.Length; i++)
            {
                Console.WriteLine("Argument # " + i + ": " + my_args[i]);
            }

            Console.ReadLine();
        }
    }
}

C# Example Code to Check if File Exist in given Directory

This C# example code will help you to check if a file exist in a given directory. For example in below code it is looking for test.txt file in test directory. C# provide inbuilt method File.Exists, which return true if file found.

C# Example Code to Check if File Exist in given Directory

using System;
using System.IO;
namespace MyApp
{
    class file_not_found_class
    {
        public static void Main(string[] my_args)
        {
            string my_file = @"c:\test\test.txt";

            if (File.Exists(my_file))
            {
                Console.WriteLine(my_file + " found.");
            }
            else
            {
                Console.WriteLine("Unable to find file: " + my_file);
            }

            Console.ReadLine();
        }
    }
}

How to Remove a Text from a String using C#

This program will help you to remove a range of characters from a string and also you can remove from a specific postion to end of string. The both methods are mentioned below.

How to Remove a Text from a String using C#

using System;
using System.Text;

namespace MyApp
{
    class remove_string_class
    {
        public static void Main(string[] args)
        {
            string strOriginal = "Software Testing Tutorials";
            Console.WriteLine("Original string: " + strOriginal);

            //specific remove
            string strNew = strOriginal.Remove(19);
            Console.WriteLine("New string: " + strNew);

            //range remove
            strNew = strOriginal.Remove(5, 15);
            Console.WriteLine("New string: " + strNew);

            Console.Read();
        }
    }
}

Thursday, March 24, 2011

How to use Stopwatch to Calculate Program Execution time in C#

The execution time is very important for a program and programmer should know the ways by which he can calculate the total program execution time. C# provide a stropwatch to calculate time. if you want to measure the time start the stopwatch before program start execution and stop the watch after program finishes the execution.

How to use Stopwatch to Calculate Program Execution time in C#

C# Code to Calculate Program Execution Time:

using System;
using System.Diagnostics;
using System.Threading;

namespace MyApp
{
    class execution_time_class
    {
        public static void Main(string[] args)
        {
           Stopwatch my_watch = new Stopwatch();

           my_watch.Start();
            for (int i = 1; i < 100; i++)
            {
                Thread.Sleep(1);
            }
            my_watch.Stop();

            Console.WriteLine("Elapsed: {0}", my_watch.Elapsed);
            Console.WriteLine("Elapsed in milliseconds: {0}", my_watch.ElapsedMilliseconds);
            Console.WriteLine("Elapsed timer ticks: {0}", my_watch.ElapsedTicks);

            Console.Read();
        }
    }
}

How to Fix Object must be of type String : ArgumentException in C#

This C# program will help you to catch C# ArgumentException. As you can see that the function accepting the object type while we are passing int type.

How to Fix Object must be of type String : ArgumentException in C#

using System;

namespace MyApp
{
    class ArgumentException_class
    {
        public static void Main(string[] args)
        {
            try
            {
                string strException = "C# ArgumentException Example";
                strException.CompareTo(123);        
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Exception: {0}", ex.Message);
            }
            Console.Read();
        }
    }
}

how to Remove Multiple Blank Spaces from a String using C# | Regular Expression

how to Remove Multiple Blank Spaces from a String using C# | Regular Expression

The below code will help developers to reduce the multiple (white)blank spaces in a string and convert into single space. This program is using regular expression to remove multiple spaces. while there is other ways are available to achieve the same.

using System;

namespace BlankSpaces_MyApp
{
    class _class
    {
        public static void Main(string[] args)
        {
            string str = " Software  Development            Using C# - C#         Tutorials ";
            string NewString = System.Text.RegularExpressions.Regex.Replace(str, @"\s+", " ");
            Console.WriteLine(NewString);

            Console.Read();
        }
    }
}

Tuesday, March 15, 2011

How to Move a File from one Directory to another Directory using C#

C# provide number of inbuilt functions for file operation. One important function is to move a file from one folder to another folder. There is two ways you can transfer a file

File.Move – use this method to directly transfer files
fobj.MoveTo - use this method in fileinfo object and move file.

image

using System;
using System.IO;
namespace MyApp
{
    class file_move_class
    {
        public static void Main(string[] args)
            {
            string source_file = @"d:\source\test.txt";
            string target_file = @"d:\target\test.txt";

            //Method 1
            if (File.Exists(source_file) && !File.Exists(target_file))
            {
                File.Move(source_file, target_file);
                Console.WriteLine("File Moved.");
            }

            //Method 2
            if (File.Exists(target_file) && !File.Exists(source_file))
            {
                FileInfo fobj = new FileInfo(target_file);
                fobj.MoveTo(source_file);
               // Console.WriteLine("File Moved.");
            }

            Console.Read();
        }
    }
}

C# Program to Copy a File into Another File

This program will help C# developers to copy a gen file into another file using C# inbuilt function. There is a direct method to copy file File.Copy,  where you need to pass source and target files path.

Another method is get the fileinfo and the then call CopyTo method of fileinfo object. The code for both the methods are given below. Please comment if you face any problem.

using System;
using System.IO;
namespace MyApp
{
    class file_copy_class
    {
        public static void Main(string[] args)
            {
            string source_file = @"d:\source\test.txt";
            string target_file = @"d:\target\test.bak";

            //Method 1
            if (File.Exists(source_file))
            {
                File.Copy(source_file, target_file, true);
            }

            //Method 2
            if (File.Exists(source_file))
            {
                FileInfo objFile = new FileInfo(source_file);
                objFile.CopyTo(target_file, true);               
            }

            Console.Read();
        }
    }
}

Sunday, March 13, 2011

How to Add Newline into a String using C#

The below code help you to add newline char in a string using two different methods. Please comment if you face any problem while using this.

How to Add Newline into a String using C#

C# Example to Add newline in a string:

using System;

namespace MyApp
{
    class newline_class
    {
        static void Main()
        {
            string site1 = "SoftwareTestingNet.com";

            string site2 = "SharepointBank.com";

            Console.WriteLine(site1 + Environment.NewLine + site2);
            Console.WriteLine(site1 + "\n" + site2);

            Console.Read();
        }
    }
}

How add Currency (Dollar) Sign to a Number using C#

This program will help you to add dollars sign before a number using C#. You can add another currency sign but you need to pass appropriate culture information. for example for us dollars pass en-US

How add Currency (Dollar) Sign to a Number using C#

C# Sample code to add $

using System;
using System.Globalization;
namespace MyApp
{
    class formatting_class
    {
        static void Main()
        {
            decimal Money = 100.20M;

            Console.WriteLine(Money.ToString("c", new CultureInfo("en-US")));

            Console.Read();
        }
    }
}

How to Set number of Decimal Places using C#

This program will help you to control number of decimal points after decimal using C#. use F and then Number of decimal points.

How to Set number of Decimal Places using C#

C# Example to control decimal point

using System;
using System.Globalization;
namespace MyApp
{
    class decimal_formatting_class
    {
        static void Main()
        {
            double myAmount = 105.245;

            Console.WriteLine(myAmount.ToString("F2", CultureInfo.InvariantCulture));
            Console.WriteLine(myAmount.ToString("F4", CultureInfo.InvariantCulture));

            Console.Read();
        }
    }
}

How to Add Leading Zeros to a Number using C#

This program will help you to add leading zero to a given number you can specify D5 if you want that total number of digits should be 5 including zeros.

How to Add Leading Zeros to a Number using C#

C# Sample Code to Add Leading Zeros:

using System;
using System.Globalization;
namespace MyApp
{
    class Leading_zero_class
    {
        static void Main()
        {
            int myAmount = 475;

            Console.WriteLine(myAmount.ToString("D6", CultureInfo.InvariantCulture));
            Console.WriteLine(myAmount.ToString("D5", CultureInfo.InvariantCulture));

            Console.Read();
        }
    }
}

Count the Numbers of Vowels in String using C#

This program will help beginners to calculate number of vowels in a given string. Please note that you need to take care of both uppercase and lowercase letters.

Count the Numbers of Vowels in String using C#

C# Code Example to Calculate Vowels:

using System;

namespace MyApp
{
    class vowels_class
    {
        static void Main()
        {
            int my_count = 0;
            Console.WriteLine("Enter a string:");
            string myString = Console.ReadLine();
            foreach (char ch_vowel in myString)
            {
                switch (ch_vowel)
                {
                    case 'a':
                    case 'A':
                        my_count++;
                        break;
                    case 'e':
                    case 'E':
                        my_count++;
                        break;
                    case 'i':
                    case 'I':
                        my_count++;
                        break;
                    case 'o':
                    case 'O':
                        my_count++;
                        break;
                    case 'u':
                    case 'U':
                        my_count++;
                        break;
                    default:
                        break;
                }
            }
            Console.WriteLine("Number of Vowels are: {0} ", my_count);
            Console.Read();
        }
    }
}

How to Start and Stop a Thread using C#

This is simple C# thread program which start and stop the thread. As you can see that after stropping the thread it is not printing next statement.

How to Start and Stop a Thread using C#

C# Program Example for Thread start and stop:

using System;
using System.Threading;
namespace MyApp
{
    class thread_class
    {
        static void Main()
        {
            ThreadStart ts = new ThreadStart(myThreadFunction);
            Console.WriteLine("Creating thread");

            Thread t = new Thread(ts);
            t.Start();

            Console.WriteLine("Starting thread");           

            Console.Read();
        }

        static void myThreadFunction()
        {
            Console.WriteLine("Calling thread");
            Thread.CurrentThread.Abort();
            Console.WriteLine("After stop thread");
        }
    }
}

How to Generate Random Filename and Extension using C#

The below program will help you to generate random file names and random extensions for those files. C# provide GetRandomFileName function to achieve the same.

How to Generate Random Filename and Extension using C#

C# Example code to generate randome file name:

using System;
using System.IO;
namespace MyApp
{
    class Extension_class
    {
        static void Main()
        {
            string my_random_file = Path.GetRandomFileName();

            Console.WriteLine(my_random_file);

            Console.Read();
        }
    }
}

How to change extension of a file using C# Program

This program will help you to change a file extension using C# code. C# provide a inbuilt method ChangeExtension to change the file extension.

As you can see in the output, the file have different extension.

image

using System;
using System.IO;
namespace MyApp
{
    class Extension_class
    {
        static void Main()
        {
            string myPath = Path.ChangeExtension(@"D:\my_file.txt", "bat");

            Console.WriteLine(myPath); 
            Console.Read();
        }
    }
}

How to use Conditional Operator in C# | Example

This program will help beginners to learn the conditional operator provided by C#. if condition is true it will give before : (colon) results otherwise give after :(colon) results.

How to use Conditional Operator in C# | Example

C# Code Example for Conditional Operator:

using System;

namespace MyApp
{
    class conditional_class
    {
        static void Main()
        {
            bool my_bool = true;
            string strResult = my_bool ? "True condition" : "False condition";
            Console.WriteLine("{0}", strResult);
            Console.WriteLine("Condition is {0}", my_bool ? "The condition is true" : "The condition is false");
            Console.Read();
        }
    }
}

How to get Path of All Windows Special Folders using C#

The below program will help you to find all special folders using C#. this program fetch values of special folder from environment variable.

How to get Path of All Windows Special Folders using C#

using System;
using System.IO;

namespace MyApp
{
    class windows_folders_class
    {
        static void Main()
        {
            foreach (Environment.SpecialFolder myfolder in Enum.GetValues(typeof(Environment.SpecialFolder)))
            {
                string mypath = Environment.GetFolderPath(myfolder);
                Console.WriteLine("{0}----{1}", myfolder, mypath);
            }
            Console.Read();
        }
    }
}

How to Combine Directory Path using C#

This Program will help you to combine directory path of a file. C# provide a method Path.Combine to combine path.

How to Combine Path using C#

using System;
using System.IO;

namespace MyApp
{
    class Path_class
    {
        static void Main()
        {
            string strpath = Path.Combine(@"C:\Windows\", "System32");
            strpath = Path.Combine(strpath, "calc.exe");
            Console.WriteLine(strpath);

            Console.Read();
        }
    }
}

How to get IP Address of Website Host using C#

Sometimes developers need IP address of website hosting server. The below code will help software developer to find out all the IP address associated with website. Do noty forget to include System.Net namespace.

How to get ip Address of Website Host using C#

C# Program to get IP Address:

using System;
using System.Net;

namespace MyApp
{
    class Pascal_class
    {
        static void Main()
        {
            string Website1 = "www.SoftwareTestingNet.com";
            string Website2 = "www.BharatClick.com";
            IPAddress[] ip_Addresses = Dns.GetHostAddresses(Website1);
            foreach (IPAddress my_address in ip_Addresses)           
            {
                Console.WriteLine("www.SoftwareTestingNet.com Address: {0}", my_address);
            }

            ip_Addresses = Dns.GetHostAddresses(Website2);
            foreach (IPAddress my_address in ip_Addresses)
            {
                Console.WriteLine("www.BharatClick.com Address: {0}", my_address);
            }

            Console.Read();
        }
    }
}

C# Lab Assignment: Program to Print Pascal triangle

This program will help beginners to write their lab assignment and print the Pascal triangle on consol. you can specify limit of Pascal triangle and the program will calculate the Pascal triangle.

C# Lab Assignment: Program to Print Pascal triangle

C# Program for Pascal triangle.

using System;

namespace MyApp
{
    class Pascal_class
    {
        static void Main()
        {
            int nLimit;
            Console.Write("Enter the limit for Pascal Triangle: ");

            nLimit = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < nLimit; i++)
            {
                int c = 1;
                Console.WriteLine(" ");

                for (int j = 0; j <= i; j++)
                {
                    Console.Write(c);
                    Console.Write("");

                    c = c * (i - j) / (j + 1);
                }
                Console.Write(" ");
            }
            Console.Write(" ");
            Console.Read();
        }
    }
}

Saturday, March 12, 2011

How to write C# Program to Print Star Triangle

This program will help beginners to write their lab assignment. You can take the logic from below given code. There is 3 loops

First loop is for printing limit and second loop is for space , third loop is for  printing star.

image

C# Program to print star triangle:

using System;

namespace MyApp
{
    class triangle_class
    {
        static void Main(string[] args)
        {
            int number = 12;

            for (int i = 1; i <= number; i++)
            {
                for (int j = 1; j <= number - i; j++)
                    Console.Write(" ");
                for (int k = 1; k <= i; k++)
                    Console.Write(" *");
                Console.WriteLine("");
            }                      
            Console.ReadLine();
        }
    }
}

How to Print a String in Uppercase and Lowercase using C#

Here is simple demo program to print a given string in uppercase and lowercase string using string inbuilt function.

How to Print a String in Uppercase and Lowercase using C#

C# Program :

using System;

namespace MyApp
{
    class Case_class
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a string:");
            string str = Console.ReadLine();

            Console.WriteLine(" Lowercase string: "+ str.ToLower());
            Console.WriteLine(" Uppercase string: " + str.ToUpper());
            Console.ReadLine();
        }
    }
}

How to Print a String Triangle using C#

This is simple program. The student get as there first lab assignment. Just writing here to help them and understand the programming logic.

How to Print a String Triangle using C#

using System;

namespace MyApp
{
    class string_triangle_class
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a string:");
            string str = Console.ReadLine();

            for (int j = 0; j < str.Length; j++ )
            {
                for (int i = 0; i <= j; i++ )
                    Console.Write(str[i]);
                Console.WriteLine("");
            }

            Console.ReadLine();
        }
    }
}

How to Calculate Compound Interest using C#

This C# program will help you to find out compound interest for given input values.

Hoe to Calculate Compound Interest using C#

Program to calculate compound interest:

using System;

namespace MyApp
{
    class compound_interest_class
    {
        static void Main(string[] args)
        {
            double Total = 0, interestRate, years, annualCompound, inAmount;          

            Console.Write("Please Enter:");
            Console.Write("Initial Amount: ");
            inAmount = Convert.ToDouble(Console.ReadLine());

            Console.Write("interest rate: ");
            interestRate = Convert.ToDouble(Console.ReadLine()) / 100;

            Console.Write("Number of Years: ");
            years = Convert.ToDouble(Console.ReadLine());

            Console.Write("Number of times the interest will be compounded: ");
            annualCompound = Convert.ToDouble(Console.ReadLine());

            for (int t = 1; t < years + 1; t++)
            {
                Total = inAmount * Math.Pow((1 + interestRate / annualCompound), (annualCompound * t));
                Console.Write("Your total for year {0} "
                            + "is {1:F0}. \n", t, Total);

            }

            Console.ReadLine();
        }
    }
}

How to Find the Second Highest Number in Array using C#

This C# program will help you to find the second highest number in C#. i tried to make it as much efficient as possible. Please comment if you have some good idea.

How to Find the Second Highest Number in Array using C#

using System;

namespace MyApp
{
    class second_highest_class
    {
        static void Main(string[] args)
        {
            int[] input_array = {-1,-5,10, 5, 20};
            int highest_number = input_array[0];
            int second_highest_number;

            if (input_array[1] > highest_number)
            {
                second_highest_number = highest_number;
                highest_number = input_array[1];               
            }
            else
            {
                second_highest_number = input_array[1];
            }

            for (int i = 2; i < input_array.Length; i++)
            {
                if (input_array[i] > highest_number)
                {
                    second_highest_number = highest_number;
                    highest_number = input_array[i];       
                }
                else if (input_array[i] > second_highest_number)
                {
                    second_highest_number = input_array[i];       
                }
            }

            Console.WriteLine("second highest number in array: {0}", second_highest_number);
            Console.ReadLine();
        }       
    }
}

Sponsored Ad

Development Updates