Showing posts with label csharp. Show all posts
Showing posts with label csharp. Show all posts

C# interview questions and answers

C# aka. "C sharp" is a programming language runs on the .NET Framework and used for building a variety of applications. C# is type-safe, powerful and object-oriented.

What is an object?

An object is an instance of a class using which we can access the properties, methods of that class. An object is created using "New" keyword. An object in memory contain the information about the methods, properties and behavior of that class.

What is Constructors?

Constructor is special method of the class which comes with same name as class.Constructor will be automatically invoked when an instance of the class is created. Constructors are mainly used to initialize private fields of the class while creating an instance for the class. If class does not contain a constructor, then compiler will automatically create a default constructor in the class that initializes all numeric fields in the class to zero and all string and object fields to null. Syntax:
[Access Modifier] ClassName([Parameters])
{
}
Example of default constructor:

public class MyClass
{
    public MyClass()
    {
    }
}


Types of Constructors

Below are the constructor types:
Default Constructor
Parameterized Constructor
Copy Constructor
Static Constructor
Private Constructor

What is the difference between ref & out parameters?

An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.

What is difference between constants and read-only

The "readonly" keyword is different than that of const keyword.
A const field can only be initialized at the declaration of the field. A "Const" field is a compile-time constant.

A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. The readonly field can be used for runtime constants.

What are value types and reference types?

Variables those holds actual data and stored on stack are "Value" types.
Ex. int, enum , byte, decimal, double, float, long

Variables those holds reference to the actual data are of "Reference" types.
Ex. string , class, interface, object

What are sealed classes in C#?

In C#, the "sealed" modifier prevents other classes to be inheriting from it.You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties

What is method Overloading?

Overloading is when you have multiple methods in the same scope, with the same name but different signatures. Also known as Compile Time Polymorphism. Ex.
//Overloading
public class OverloadClass
{
    public void someMethod(int id)
    {}
    public void someMethod(string name)
    {}
}

What is method Overriding?

Functions in the extended class with same name and same parameters as in the base class, but with different behaviors. Ex.
//Overriding
public class OverridingClass
{
   public virtual someMethod(int id)
   {
      //Get stuff default location
   }
}

public class test2 : test
{
   public override someMethod(int id)
   {
       //base.getStuff(id);
       //or - Get stuff new location
   }
}

What is the difference between Array and Arraylist?

In an array, we can have items of the same type only. The size of the array is fixed. An ArrayList hold data type of an object, So using array with different types can cause runtime error. It does not have a fixed size.

Which are Access Modifiers available in C#?

All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies.
You can use the following access modifiers to specify the accessibility of a type or member when you declare it:

public: The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private: The type or member can be accessed only by code in the same class or struct.
protected: The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.

What is static constructor?

Static constructor is used to initialize static data members as soon as the class is referenced first time. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.

What is Reference Type in C# ?

Let us explain this with the help of an example. In the code given below,
Employee emp1;
Employee emp2 = new Employee();
emp1 = emp2;
Here emp2 has an object instance of Employee Class. But emp1 object is set as emp2. What this means is that the object emp2 is referred in emp1, rather than copying emp2 instance into emp1. When a change is made in emp2 object, corresponding changes can be seen in emp1 object.

What is Abstract Class in C#?

If we don't want a class to be instantiated, define the class as abstract. An abstract class can have abstract and non abstract classes. If a method is defined as abstract, it must be implemented in derived class. For example, in the classes given below, method DriveType is defined as abstract.
abstract class Car
{
 public Car()
 {
  Console.WriteLine("Base Class Car");
 }
 public abstract void DriveType();
}

class Ford : Car
{
 public void DriveType()
 {
  Console.WriteLine("Right Hand ");
 }
}
Method DriveType get implemented in derived class.

What is Sealed Classes in c# ?

If a class is defined as Sealed, it cannot be inherited in derived class. Example of a sealed class is given below.
public sealed class Car
{
 public Car()
 {
  Console.WriteLine("Base Class Car");
 }

 public void DriveType()
 {
  Console.WriteLine("Right Hand ");
 }
} 

What is the use of var keyword in C#?

This is the new feature in C# 3.0. This enable us to declare a variable whose type is implicitly inferred from the expression used to initialize the variable.
eg.
var age = 10;
Because the initialization value (10) of the variable age is integer type of age will be treated as integer type of variable. There are few limitation of the var type of variables.

Dynamic in C# 4.0

Dynamic type is introduced C# 4.0. As its name specifies type of the defined variable is decided dynamically at runtime. At compile time the variable that is declared as dynamic is assumed to be support any type or operation. As it does everything at runtime if code is not valid then errors are caught at runtime. Two major disadvantages of dynamic type are No compile time checking and No intelliSense support

Dynamic type example

Suppose we have class called SomeClass that have methods Method1() and Sum(intx, int y).
    public class SomeClass
    {
        public SomeClass()
        {
        }

        public void Method1()
        {
            //Do something
        }

        public int Sum(int x, int y)
        {
            return x + y;
        }
    }

and we are now trying to use the above class using dynamic type.
    public partial class DynamicType : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            dynamic someclass_dy = new SomeClass();
           
            someclass_dy.Method1();

            someclass_dy.Sum(10, 3);

            someclass_dy.SomeOtherMethod();
        }
     }

In above code we have defined dynamic type object of class SomeClass(). and now if you try to access methods from that class it will not show any method in intelliSense, you explicitly need to know the class methods and call them that is because dynamic type does not supports compile time checking. If you notice there is code line someclass_dy.SomeOtherMethod(); where SomeOtherMethod() does not exists in SomeClass() still it will not throw any compile time error, but it will throw runtime error.


Tuple in C# 4.0

Tuple is a new class introduced in C# 4.0. Tuple basically provides way to group the items of different data types. A static Tuple class provides 8 overloads of create method to create Tuple of size 1 to 8. Also using new keyword and nesting tuples you can create more sized Tuple. Now for example tuple created with 3 elements called 3-tuple or triple that can hold three elements of any type. So first element may be firstname that is string, second element may be phone number that is int and salary which is double may be the third element. And we can read those values using item property of tuple like for 3-tuple it will tuple.Item1, tuple.Item2 and tuple.Item3.

Tuple example 3-tuple

     var tuple3 = new Tuple("Johan", 1234567890, 56000.90);
     Console.WriteLine(tuple3.Item1);
     Console.WriteLine(tuple3.Item2);
     Console.WriteLine(tuple3.Item3);

In above example it will print
Output:
  Johan
  1234567890
  56000.90

Lazy loading C#. Lazy initialization.

C# 4.0 introduced new class Lazy which provided for Lazy initialization. Lazy instantiation here means object is not created until it is get used first time. Primary use of Lazy initialization is performance improvements, reduce program memory requirements.Lazy provides thread safe object initialization.

Lasy<T> example to load object lazily

public partial class LazyClass : System.Web.UI.Page 
{
 private Lazy<List<string>> lazyItems = null; 
 public LazyClass() 
 { 
   lazyItems = new Lazy<List<string>>(GetItems); 
 } 
 public List<string> GetItems() 
 {
      List<string> items = new List<string>(); 
      for (int i = 0; i < 10; i++) 
       { 
          items.Add(string.Format("Item {0}", i)); 
       } return items;
 }

 public List<string> GetItemValues { get { return lazyItems.Value; } } 
}

So in above example we have defined private Lazy<List<string>> lazyItems = null; and then in constructor we have delegate the call to GetItems method which will return list of items. But here it will not generate and return list until we call "lazyItems.Value".


Validate email format - RegularExpressionValidator

In asp.net in order to validate email address format we can use RegularExpressionValidator. We will see how to use RegularExpressionValidator to validate the email address format.For that we need to specify the Regular expression or regex in ValidationExpression property of the RegularExpressionValidator. Also we need to specify few other properties like ErrorMessage to display error message when email address is invalid. also we need to specify ControlToValidate property where we have to give textbox controls name in which user enters email address.

Validate email address using regular expression validator

Example to validate email address using RegularExpressionValidator

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Validate email format </title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:TextBox ID="txtEmail" runat="server" />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    <asp:RegularExpressionValidator ID="validateEmail" runat="server" ErrorMessage="Invalid email."
      ControlToValidate="txtEmail" ValidationExpression="^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" />
  </div>
  </form>
</body>


Also we need to check !Page.IsValid in event hadler of control like button or link...etc like
  protected void btnSubmit_Click(object sender, EventArgs e)
    {
      if (!Page.IsValid)
        return;
    }

c# regex for email address

In c# while dealing with email we need to validate email address. In order to validate email address we just check whether the email address format is correct or not. In C# we can use System.Text.RegularExpressions namesapce to match the email address for validation. In Regular Expressions namespace we have Regex class and from which .Match() method can be used to match the email address with the regular express defined using Regex class.

c# regex for email address

C# code to validate email format.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>C# validate email format regex</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="txtemail"></asp:TextBox>
        <asp:Button runat="server" ID="Send" OnClick="Send_Click" Text="Send" />
    </div>
    </form>
</body>
</html>

using System;
using System.Text.RegularExpressions;
public partial class Csharpregularexpressionemail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Send_Click(object sender, EventArgs e)
        {
            ValidateEmail();
        }
        private void ValidateEmail()
        {
            string email = txtemail.Text;
            Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
            Match match = regex.Match(email);
            if (match.Success)
                Response.Write(email + " is corrct");
            else
                Response.Write(email + " is incorrct");
        }
    }


In above example we have specified format for email regex using constructure call of Regex class. Then we have used .Match method to match the regular express pattern for email to match. And after that we have checked if match is successfull or not.

C# convert array to list

In this post we will se how to convert array to list. We need to convert array object to generic list many times in C# programming. Converting array to list can be done by various ways. We are going to see C# examples to convert array to the list.

Conversion of array to an list can be done using constructor of the generic List class. We here use constructor of List and pass array object as parameter to List constructor and then convert it to List>

c# array to list
.

Example - convert array to list [C#]:

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
// String array to convert to list
 string[] strarr = new string[]
 {
  "Convert",
  "Array",
  "To",
  "list",
 };

//Now we will convert above array using new list constructor.
 List<string> arrayToList = new List<string>(strarr);
}

In above example we saw how we converted array to list using List constructor. Now we will see other way to convert Array to list. In this way we use .ToList() instance method that converts array to list. Below example shows how array get converted in to list using .ToList() parameter less instance method.

Example to convert array to list [C#]:

using System;
using System.Collections.Generic;

class Program
{    
static void Main()
{    
// String array to convert to list    
 string[] strarr = new string[]    
 {
  "Convert",
  "Array",
  "To",
  "List",
 };
//Now we will convert above array using .ToList instance method.
List<string> arrayToList = strarr.ToList();
}

String splitting C#

split string c#

C#.Net provides Split() function to split the string by the specified char and stores it in array. Split string using C# is bit easy task. In C# we can split string into substrings—such as splitting a sentence into individual words. In this case we set split char as a "," character and then it will returns an array of substrings

using System;
public class sortlist
{
  public static void Main()
  {
    string myString = "C#,VB,ASP.NET,C++";
    string[] splitedString = myString.Split(‘,’); 
    foreach(string item in splitedString)
    {
     Console.WriteLine(item);
    }
  }
}

//Output
//C#
//VB
//ASP.NET
//C++

C# sort list [Generic List<T>]

c# sort list
Generic List in C# provides easy way to sort list. In C# some times we need to add data to generic list and sort list by ascending based on our need. C# .net provides .sort method for List that can be used for sorting the contents of list. We will see example to sort list in c#.

Sample code to sort list [C#]:


using System;
using System.Collections.Generic;

public class sortlist
{
public static void Main()
{
List<string> names =  new List<string>();
names.Add("John");
names.Add("Antony");
names.Add("Mickel");
names.Add("Daniel");
names.Sort();
Console.WriteLine();
foreach(string name in names)
{
Console.WriteLine(name);
}
}
}


//Output
//Antony
//Daniel
//John
//Mickel

List to array c#

array to list
In this post we will se how to convert list to array.We need to convert list to array many times in C# programming. Converting list to array can be done by various ways. We are going to see C# examples to convert the list to array.

we will see the way to convert list to an array. we use .ToArray() parameter less instance method that converts list to an array. Below example shows how list get converted in to array using .ToArray() method:

Example to convert list to array [C#]

using System;
using System.Collections.Generic;

class Program
{
 static void Main()
 {
  // List to convert into Array.
  List<string> lstString = new List<string>();
  lstString.Add("Convert");
  lstString.Add("List");
  lstString.Add("TO");
  lstString.Add("Array");
  // use .ToArray() Method to convert list to array
  string[] strArray = lstString.ToArray();
 }
}

Array to List [C#]

convert array to list

Some times we need add elements of an array to list in C# programming. We can use .Add() method of List class to add array elements to the List.Using . we also can use .Add() method to while converting array to List.

We will see example that will show how used .Add method to convert array to List. Here we iterate through array elements and then one by one we add those elements to List.



using System.Collections.Generic; 

protected void Button1_Click(object sender, EventArgs e) 
{     
 string[] arrStr = { "Add", "Array", "Elements", "To", "List", "C#" };      
 List <string> strList = new List<string>();     
 foreach (string stritem in arrStr)    
 {          
  lstString.Add(stritem);    
 }      
}

Write to text file [C#]

c# write to text file
File class in System.IO Namespace also contains methods to write contents to text tile. WriteAllText() method to write string to text file. WriteAllLines() method is used to write line by line into text file. And WriteLine() method writes or appends text to the text file with existing contents.
How to write to a text file?
TO write to a text file in file system .net has provided below methods in File class of System.IO namespace:
1.WriteAllText.
2.WriteAllLines.
3.WriteLine.

1.WriteAllText.

WriteAllText method in File class writes one string to the text file

Sample code that shows how to write into to text file[C#]

class WriteFileAllText
{
 static void Main()
 {
  // Example to Write one string into text file.
   string textToWrite = "To write one string into a text file use 
   WriteAllText method, " ;
   System.IO.File.WriteAllText(@"C:\\TextFileFolder\NewTextFile.txt", textToWrite);
 }
}  

2.WriteAllLines.

WriteAllLines method in File class writes contents to a text file line by line.

Sample code that show how to write into a text file line by line[C#]

class WriteFileLines
{
 static void Main()
 {  
  // Example to Write the contents line by line into text file.
  string[] lines = {"Line One", "Line Two", "Line Three"};
  System.IO.File.WriteAllLines(@"C:\TextFileFolder\WriteLines.txt", lines);}
 }  

3.WriteLine.

WriteLine method in File class writes or appends line to a text file that already have some data.

Sample code that show how to append text line into a text file.[C#]

It uses StreamWriter class of System.IO namespace to append line in existing text file
class WriteFileLine
{
static void Main()
{  
 // Append text line to existing file
 System.IO.StreamWriter file = new System.IO.StreamWriter ("C:\TextFileFolder\WriteLines.txt", true)
 {
  file.WriteLine("Line Four");
 }
}

C# Uppercase First Character or Letter

uppercase first letter in string

Some times we need to uppercase the first letter. There are various ways to make first word in uppercase. we will look at some of the ways to uppercase the first letter in strings in the C#. We can take out first character of string from it’s zero index and the using char.ToUpper(str[0]) we can capitalize first character and then concatenate it with remaining string and make string again. Other way to uppercase first character or letter is use .ToCharArray() method and then from array of characters take zero index character make it uppercase and then formulate new string again. Other alternative is to use Substring() method and take characters from position 0 to 1 and capitalize first character and then using substring from 1 position concatenate those strings.

Here we will see how first way will work to uppercase first character or letter of the string using c#.

C# code to uppercases first character

using System;
class Program 
{ 
 static void Main()
 {
  Console.WriteLine(UppercaseFirstLetter("first")); 
 }
 static string UppercaseFirstLetter(string str)
 {
  var  firstChar = str[0];
  var  UpperCaseFirstCharacter =  char.ToUper(firstChar);
  var convertedFirstCharToUpper = UpperCaseFirstCharacter +  str.Substring(1);
  return convertedFirstCharToUpper ;
 }
}


//Result:
//First.

In above code sample for upper case first letter we first take first char as str[0] and using char.ToUpper(str[0]) we Capitalized first character and then concatenated remaining string with first capitalized char and the returns the new string with first letter capitalized.


Second way to Uppercase the First latter of the String:


C# code to uppercases first letter


using System;

class Program
{
 static void Main()
 {
  Console.WriteLine(UppercaseFirstCharacter("first"));    
 }

 static string UppercaseFirstCharacter(string str)
 {
  char[] strArray = str.ToCharArray();
  strArray[0] = char.ToUpper(strArray [0]);
  return new string(strArray);
 }
}


//Result
//First.

In above C# code we have converted input string in to array of characters using .ToCharArray() and then took zero index character and uppercase it and the formed new string with new string constructor to construct string.

Third way to uppercase first character of string using c#

C# code to uppercases first character [C#]


public static string Capitalize(string input)   
{
 str = "first";
 return str.Substring(0, 1).ToUpper() + str.Substring(1);
}


//Result:
//First

In above C# example to uppercase first character of string we used Substring() method. using Substring(0,1) we get first character of string and then we capitalized that character like Substring(0,1).ToUpper() and then we concatenated remaining string from first position onwards to it.

C# string ToLower - Convert string to lowercase

c# string tolower

While writing C# code some times we need a string to be converted to lowercase string, so that the uppercase letters of the string get converted to lowercase letters. This is useful when you need to compare the string with lowercase string. It is good practice to make comparing strings to be convert to uppercase or lowercase if we don’t know how input is coming. We will see how to convert all letters to small case in the string using ToLower function in C#.

C# code that shows how to use ToLower [C#]


using System;
class Program
{
 static void Main()
 {
  string str = "C# STRING LOWERCASE EXAMPLE";
  string upStr = str.ToLower();
  Console.WriteLine(upStr);
 }
}

Result
c# string lowercase example


The ToLower function or method converts all the uppercase characters in the string to lowercase characters, If string contains some lowercase letters or characters it ignores them. We will see how to compare two strings by using lowercase to the input string.

using System;

class Program
{
 static void Main()
 {
  string str = "C# STRING LOWERCASE";
  string upStr = str.ToLower();
  if("c# string lowercase” == upStr)
  Console.WriteLine("Strings are equal.");
 }
}


Result
Strings are equal.

C# string ToUpper - Convert string to uppercase

c# string toupper

In some cases we need to convert lowercase string to uppercase string, so that the lowercase letters of the string get converted  to uppercase letters. We can uppercase string using c# string ToUpper Method This is useful when you need to compare the string with uppercase string. It is good practice to make comparing strings to be convert to uppercase or lowercase if we don’t know how input is coming. We will see how to capitalize all letters in the string using ToUpper function in C#.


C# code that shows how to use ToUpper [C#]


using System;

class Program
{
static void Main()
{
string str = "C# string uppercase example";
string upStr = str.ToUpper();
Console.WriteLine(upStr);
}
}

//Result
//C# STRING UPPERCASE EXAMPLE


The ToUpper function or method converts all the lowercase letters in the string to uppercase letters, If string contains some uppercase letters or characters it ignores them. We will see how to compare two strings by using uppercase the the input string.


using System;

class Program
{
static void Main()
{
string str = "C# string uppercase";
string upStr = str.ToUpper();
if("C# STRING UPPERCASE” == upStr)
Console.WriteLine("Strings are equal.");
}
}

//Result
//Strings are equal.

Some time you may need to just upper case the first latter or character of the string. In that case we can use ToCharArray method and the for first character user char.ToUpper().

C# string

C3 strings
C# string is a object of class String. Value of string is text, which is nothing
but the collections of read-only char Objects. In C# we can do various string operations like
strings splitting, string indexOf, string reverse, string format , we can also use string .ToUpper()
to make string in upper case in C#, also we can use string .ToLower() to make string in
lower case in C#. String also has Trimmimg functions. we can trim the string in
c# using these functions. We will discuss most of these function to perform operations
on string using c#.

C# string is alias for System.String so String and string are equivalent
to each other. The Length property of string shows number of char objects
the string contains. C# string provides lot’s of methods to create and to manipulate,
to compare, to split…etc.


C# string is immutable, means we can not change contents of string once object
is get created. When ever we change the contents of string new object of string
get created. We will see examples of c# string operations and manipulations. Below
samples will show how to make string in upper case in c# and how to make string
in lower case.

1. ToUpper() method is used to convert string in upper case.

Sample code to shows how to convert string to upper case[c#]


string myString = "This is C# string" 
string toUpperString = myString.ToUpper(); 

2. ToLower() method is used to convert string in lower case. Below example
shows how to convert string in lower case:


string myString = "This is C# string"
string tolowerString = myString.ToLower();


3. Trim() method is used to remove all white spaces from both start and end
of the string. 

string myString = " This is C# string "
string trimedString = myString.Trim();

TrimStart() method is used to trim string at start of string and TrimEnd()
is used to trim the string at the end.

TrimStart() C# example:


string myString = " This is C# string ";
string trimedString = myString.TrimStart();

TrimEnd() C# example:


string myString = " This is C# string " ;
string trimedString = myString.TrimEnd(); 

We can strip out specified characters from start of the string or at the end of
the string. Example below shows how to strip out characters from start and end position
TrimSart() C# example:


string myString = " This is C# string "; string 
trimedString = myString.TrimStart(); 
4. Replace() function used to replace string/char from the given string.

string myString = "This is VB string";
string newString = myString.Replace(“VB”, “C#”);


//Above line of code will replace “VB” by “C#”. 

5. Split() function used to split the string by the specified char and stores
it in array. Below code will split string by “,” and will store result in array
of string. Splitting a string into substrings—such as splitting a sentence into
individual words—is a common programming task. The Split() method takes a char array
of delimiters, for example, a space character, and returns an array of substrings.


string myString = "C#,VB,ASP.NET,C++";
string[] splitedString = myString.Split(‘,’); 

6. ToString() method provided by string class converts a value to a string.
Below C# code shows how .ToString() will convert numeric values into string:


int year = 1999;
string msg = year.ToString();

7. Substring() Function finds the specified characters form the string starts from 0 of the string to the used position. Substring functions takes integer parameter, which specifies from what position we need to substring the string. Below Substring sample code shows how to get substring from 8th position till end:


string myString = " This is C# string "
string newSubString = myString.Substring(8);

So result of substring of above code will take string “C# string”. We can also specify
the range from which position to which position we need to get substring.

Example below how Substring() works in c#:


string myString = " This is C# string ";
string newSubString = myString.Substring(8, 2);
Result of above code will be string “C#”. 

8.IndexOf() function is used to find String within string and returns index
position of the string. If specified character or string has not found in string
then it returns -1 index.


string myString = " This is C# string ";
int newSubString = myString.IndexOf (“C#”);
Above code will return 8th index position.

9. ToCharArray() Copies the characters in this instance to a Unicode character
array. We can use then this array to reverse the string.Below is the C# code to
Reverse the string


string myString = "string";
char[] stringArray = myString.ToCharArray();
Array.Reverse(stringArray);
string
newString = new string(stringArray);


Result of above code is “gnirts”.

Concatenate strings:In C# we can "add" two strings of text together
to create one string. The process of adding two strings together is called string
concatenation.


string s1 = "Learn C# ";
string s2 = "Strings";
string newString = s1 + s2;
So newString will hold the concatenated string “Learn C# Strings”.

The @ SymbolThe @ symbol tells the string constructor to ignore
escape characters and line breaks. The following two strings are therefore identical:

string p1 = "\\\\My Documents\\My Files\\";
string p2 = @\\My Documents\My Files\

embed resources like .js, .css or images in c#

C# embedded .js, .css , image resources

In this post we will learn how to embed the resources like javascript file, images, .css files in class libraries. When creating custom controls sometimes we need to provide resources like .js, .css and images along with control or class library assembly.


Below are the step by step example of how to embed .js file as resource and access it using WebResource.axd.

1. In Visual Studio, create a new project with selection as class library project. And Name it as ImageControl.

2. Add references like System.Web, System.Web.UI, System.Web.UI.WebControls..etc which are you think you need for creating controls.

3. Add image file e.g. image1.gif, then right click on image, go to properties and setBuild Action to Embedded Resource. Setting build action to embeddedd resource is important part while embedding resources in controls or in class libraries.

4. If you want javascript file in class library as embedded resource then add .js file e.g. script1.js in the project then add some code to it like:

function ClickMe() 

{
  alert("Hey, I get called by embedded js and I am available through web resources");
} 


5. Now next step is to right click on js file go to properties and set it's Build Action to Embedded Resource. As mentioned above it is important to set action build to embedded resource in controls or in class libraries.

6. Now add one style1.css file in project and follow the same steps to make it embedded resource like right click on css file, goto it's properties and set it's Build Action to Embedded Resource.
e.g.:
body
{
 font-family:Verdana;font-size:x-large;font-weight:bolder;color:Blue;
}

7. In order to access these embedded resource files we can use WebResource. For that we need to do one important thing that we need to add WebResources properties in assemblyinfo.cs of class library or on the class libary page itself just before namespace starts lik:
In AssemblyInfo.cs of the projects properties folder add some think like below at the end of the file.

[assembly: WebResource("ImageControl.Images.image1.gif", "img/gif")]
[assembly: WebResource("ImageControl.Scripts.script1.js", "text/javascript")]
[assembly: WebResource("ImageControl.Css.style1.css", "text/css")]


Here in ImageControl.Scripts.script1.js, ImageControl is the assembly name, Scripts is the folder in which we keep the and after that javascript file name. And is same for other resources.

8. Now to refer these resouces in control we need to do following things.
a. To refer .js file we may do like below in the controls code:

string jsResource = "ImageControl.Scripts.script1.js"; this.Page.ClientScript.RegisterClientScriptResource (this.GetType(), jsResource);

b. To refer to image file we can do like:

Page.ClientScript.GetWebResourceUrl(typeof(ImageControl.ImageHolder), ImageControl.Images.image1.gif"));

c. To refer to .css file we need to do like:
string cssResource = "ImageControl.Css.script1.css";
string cssResourceURL = Page.ClientScript.GetWebResourceUrl(this.GetType(), cssResource);

And in order to add it like

HtmlLink cssLink = new HtmlLink();
 cssLink.Href = cssResourceURL;
 cssLink.Attributes.Add("rel", "stylesheet");
 this.Page.Header.Controls.Add(cssLink);
 

Below id the sample that creates Image control in which we have image, .js and .css as embedded resources. And we are accessin it using WenResource.axd.

using System;
using System.Web.UI.WebControls;
using System.Web.UI;

[assembly: WebResource("ImageControl.Images.image1.gif", "img/gif")]
[assembly: WebResource("ImageControl.Scripts.script1.js", "text/javascript")]
[assembly: WebResource("ImageControl.Css.style1.css", "text/css")]

namespace ImageControl
{
    public class ImageHolder : Image
    {
        protected string _message;
        protected string _toolTip;
        protected bool _showBigIcon = true;
        public ImageHolder()
        {
        }
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Src,
            Page.ClientScript.GetWebResourceUrl(typeof(ImageControl.
            ImageHolder), "ImageControl.Images.image1.gif"));
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "ClickMe()");
            writer.AddAttribute(HtmlTextWriterAttribute.Alt,
            "I am embedded Image and you are watching me from Web Resource");
            base.AddAttributesToRender(writer);
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            string jsResource = "ImageControl.Scripts.script1.js";
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(),
            jsResource);
            //To add the CSS file to the custom control
            string cssResource = " ImageControl.Css.style1.css";
            string cssResourceURL = Page.ClientScript.GetWebResourceUrl
            (this.GetType(), cssResource);
            HtmlLink cssLink = new HtmlLink();
            cssLink.Href = cssResourceURL;
            cssLink.Attributes.Add("rel", "stylesheet");
            this.Page.Header.Controls.Add(cssLink);
        }
    }
}


Now to test our Image Control and embedded resources we need to add reference of class library project or dll and need to set below things in Web Project.

1. In web .config add below lines of code :
<pages>
<controls>
<add namespace="ImageControl" assembly="ImageControl" tagPrefix="myImage"/>
</controls>
</pages>
<add assembly="ImageControl" namespace="ImageControl" tagprefix="myImage" />
</controls></pages>
2. And In aspx page
3. < myImage:ImageHolder ID="img1" runat="server"/>

After running code we will get image displayed on page which is embedded and also calls javascript function for embedded .js and will show font that set in embedded .css file on the control.

C# read text file

In this post we are going to discuss how to read text file in c#. .Net provides File class in System.IO namespace which contains methods to read file from the disk.
We can read all the contents of text file in one go using ReadAllText() method of File class.
Also we can use ReadAllLines() method of File class and read each line of the file and store it in the string array and then by iterating through string array we can show each line.
System.IO namespace also contains StreamReader class which has ReadLine() method that we can use to read a Text file one line at a time.We will now see code samples to read file in C# by all the ways we discussed above.


Sample code to read text file in one go [C#]


We will use here ReadAllText() method in File class read all the contents of text file as one string [C#]

class ReadFile
{
 static void Main()
 {
   // Example to Read the file as a whole string.
    string fileText =  System.IO.File.ReadAllText( @"C:\MyFolder\TextFile.txt"); 
   // Show read content of text file in text box .
    TextBox1.Text = fileText ;
}
}

Sample code to read text file in line by line in string array [C#]

we will use here to read all lines by line in text file using ReadAlllines() method in File class.


class ReadFileLines
{
 static void Main()
{ 
   // Example to Read the file lines into a string array.
   string[] allLines = System.IO.File.ReadAllLines (@"C:\MyFolder\TextFile.txt"); 
   //Write text file contents to text box
  foreach(string line in allLines)
  {
   TextBox.Text += "\t\n" + line;
  }
 }
}

we will now look how we can use ReadLine() method of StreamReader class to read each line of text file.


Sample code to read each line of text file [C#]


int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine (line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
System.Console.ReadLine();

delete folder, directory c#

In order to remove a directory or folder using C#, .Net framework provides System.IO namspace which provides Directory.Delete method.
Directory.Delete
is a static method that gives you easy way to delete or remove folder or directory. Also we can delete directory or folder using DirectoryInfo class of System.IO namespace.

Examples of deleting directory or folder Directory.CreateDirectory:

Following is sample code for deleting or removing directory or folder on root i.e. at C:/ drive

using System.IO;

class DeleteFolder
{
static void Main()
{

// Delete Directory/folder on C:\ Drive.
Directory.Delete("C:\\TestDirectory");
}
}


Sample code to delete directory using System.IO DirectoryInfo class

using System.IO;

class CreateNewFolder
{
static void Main()
{

// Get Directory info or folder info.
DirectoryInfo dir = new DirectoryInfo(@"c:\TestDirectory");
dir.Delete();
}
}

Create new folder, directory

create folder c#
In this post we will see how to create create folder or directory using C# on server to perform some operations dynamically. .Net provides System.IO namespace to perform operation related to file system. System.IO namespace also provides ways to create new folder or directory.In order to create a directory or new folder using C#, we can either use Directory.CreateDirectory method of the System.IO namespace or we can use DirectoryInfo class of System.IO namespace.


Directory.CreateDirectory is a static method that gives you easy way to create new folder or new directory. we will see example of creating new directory or folder using Directory.CreateDirectory:

Sample code that shows how to create directory or folder on root i.e. at C:/ drive


usingSystem.IO;
class CreateNewFolder
{
 static void Main()
 {
   // Create new Directory or folder on C:\ Drive.
   Directory.CreateDirectory("C:\\TestDirectory");
 }
}

We can also add subfolders to the existing folder, so below C# code shows how to create subdirectory or sub folder in existing folder.


using System.IO;
class CreateNewFolder
{
 static void Main()
 {
   // Create new Directory or folder on C:\ Drive.
   Directory.CreateDirectory("C:\\TestDirectory\\SubFolder");
}
}

There are also alternative ways to create sub directory or sub folders. We can create directory or folder using DirectoryInfo class of System.IO namespace.

Sample code to create directory using System.IO DirectoryInfo class

using System.IO;
    class CreateNewFolder
    {
    static void Main()
    {
    // Get Directory info or folder info.
    DirectoryInfo dir = new DirectoryInfo(@"c:\TestDirectory");
    dir.create();
    }
    }