Sponsored Ad

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();
        }       
    }
}

C# Program to Find Smallest Number of a Numeric Array

The below program will help you to find minimum number of a numeric array. This is efficient program and will work for negative and positive numbers both.

Please comment in case of any questions.

C# Program to Find Smallest Number of a Numeric Array

using System;

namespace MyApp
{
    class min_class
    {
        static void Main(string[] args)
        {
            int[] number_array = {-1,-5,10};
            int minimum_number = number_array[0];

            foreach (int int_num in number_array)
            {
                if (int_num < minimum_number)
                {
                    minimum_number = int_num;
                }               
            }
            Console.WriteLine("minimum number in array: {0}", minimum_number);
            Console.ReadLine();
        }       
    }
}

How to Find max Number of int Array using C#

Do you want to find the maximum number of an integer array here is C# code to help you to find the maximum number. This code also take care of negative values also.

Please comment in case you have some better solution.

C# Code to find max Number:

using System;

namespace MyApp
{
    class my_class
    {
        static void Main(string[] args)
        {
            int[] my_number = {-1,10,2};
            int max_number = my_number[0];

            foreach (int inum in my_number)
            {
                if (inum > max_number)
                {
                    max_number = inum;
                }               
            }
            Console.WriteLine("max number in array: {0}", max_number);
            Console.ReadLine();
        }       
    }
}

How to Interchange Values of Two Variables Without using Third Variable using C#

If you looking to save memory and don't want to use third variable you can follow the below approach to swap two numbers. Please note that it is tricky interview question also.

How to Interchange Values of Two Variables Without using Third Variable using C#

using System;

namespace MyApp
{
    class my_class
    {
        static void Main(string[] args)
        {
            int intOne = 1;
            int intTwo = 2;

            intOne = intOne + intTwo;
            intTwo = intOne - intTwo;
            intOne = intOne - intTwo;

            Console.WriteLine("intOne : {0}", intOne);
            Console.WriteLine("intTwo : {0}", intTwo);

            Console.ReadLine();
        }       
    }
}

How to Fix C# Error: Cannot implicitly convert type 'string' to 'bool'

While programming suddenly i got the error : Cannot implicitly convert type 'string' to 'bool'. Then i relies that C# usage == (double equal to ) as a compare operator while = (single equal to ) is a assignment operator. So take care of this type of mistakes.

Program with error:

using System;

namespace MyApp
{
    class my_class
    {
        static void Main(string[] args)
        {
            String objstr1 = "SharePointBank.com";
            String objstr2 = "How2Sharepoint.com";

            if (objstr1 = objstr2)
            {
                Console.WriteLine("Equal.");
            }
            else
            {
                Console.WriteLine("Not Equal.");
            }               

            Console.ReadLine();
        }       
    }
}

Correct Program:

image

using System;

namespace MyApp
{
    class my_class
    {
        static void Main(string[] args)
        {
            String objstr1 = "SharePointBank.com";
            String objstr2 = "How2Sharepoint.com";

            if (objstr1 == objstr2)
            {
                Console.WriteLine("Equal.");
            }
            else
            {
                Console.WriteLine("Not Equal.");
            }               

            Console.ReadLine();
        }       
    }
}

How to Fix C# Error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

I was trying to compile the below code while i got the error. basically this error occur when you try to use a keyword as statement. you should make it statement for example in below code i have null as statement either you should assign null in a variable or write a statement. only null is not an statement.

to remove error replace

  null;

to

str3 = null;

Now compile it will work.

C# Program With Error:

using System;

namespace MyApp
{
    class my_class
    {
        static void Main(string[] args)
        {
            String str1 = "SoftwareTestingNet.com";
            String str2 = "TestingWiz.com";
            String str3;

            if (str1 == str2)
            {
                Console.WriteLine("Equal.");
            }
            else
            {
                null;
            }                  

            Console.ReadLine();
        }       
    }
}

string vs System.String : C# Interview questions

Today i got a question that what is difference between string vs System.String . suddenly i was not able to recall it. i went to my laptop and tried with a program and find out the both are same. string is alias for System.String. 

Same there is number of alias C# provide. you can go to msdn and check it.

string vs System.String : C# Interview questions 

 

using System;

namespace MyApp
{
    class my_class
    {
        static void Main(string[] args)
        {
            System.String str1 = "abc";
            string str2 = "abc";

            Console.WriteLine(str1);
            Console.WriteLine(str2);               

            Console.ReadLine();
        }

    }
}

Sponsored Ad

Development Updates