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.

jquery attribute selectors

How to Use jQuery Selectors?


jQuery has power of  minimizing lines of code. jQuery would be the powerful tool for the DOM. jQuery is easy to select elements using selector engine, it’s easy syntax, which is based on the same syntax you would use to select elements in CSS by borrowing from CSS 1-3. jQuery  selects or finds element on page by Element Id, it is jQuery option to getElementById. By using get element by id selector jQuery uses elements Id. Other selector jQuery uses is Get element by class. In this jQuery selector class name of the  element is used to access the elements on page. jQuery also get element by attribute. Also by using hierarchy jQurey selects element on page. jQuery has filters that are also useful to get elements.We will see some samples of different types of selectors.

Element by ID         jQuery getElementByID     


In the example below we will see a selection of an element by id.It is same as java scripts getElementById(). Using the id of element jQuery gets element on the page.It has every easy syntax.

<html>
<head>   
<title>Get Element by ID</title>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script> 
<script type="text/javascript">     
//get element by it's ID   
alert($("#message").text()); // Hello jQuery  
</script>
</head> 
<body>    
<div id="message">Hello jQuery</div>  
</body>  
</html>




 



jQuery uses the native JavaScript function getElementById(), for id selectors. The fastest way to select an element is to reference it by its id selector.
It’s also important that your id should not contain the special characters like:
#;&,.+*~':"!^$[]()=>|/
The characters above if not properly escaped ay confuse the jQuery selector engine as it is a different type of selector. You can use escape character way like below to handle special characters.

$(“#some:id”) -> $(“#some\\:id”)

 

Get Elements by its class


In below example we will select all elements on the page that have the specified class name. jQuery uses the class of element and get the element from the page.
jQuery GetElement By Class

<html>  
<head>  
<title>Get Element by class selector</title>  
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script>  
<script type="text/javascript">  
//Get  the element by it's classname   
alert($(".message ").text()); // HellojQuery  
</script>  
</head>  
<body>  
<p id="hello">  
<span class="message">Hello</span> <span class="message">jQuery</span>  
</p>  
</body>  
</html>  



In above example, selector matched both the span elements that have class= “message” and combined contents into one result ‘HellojQuery’.

jQuery will use the native JavaScript function GetElementsByClassName().

 

Get Elements by Attribute


Below example shows how to select elements that have an attribute with some specific value.

<html>  
<head>  
<title>Get Element by its attribute</title>  
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script>  
<script type="text/javascript">  
//get  elements by its attribute   
alert($("input[name= name]").val()); // johan   
</script>  
</head>  
<body>  
<form>  
<p> Name: <input type="text" name="name"  value="Johan" />  </p>
<p> Phone: <input type="text" name="phone" value="0000000" /> </p>
</form>  
</body>  
</html>  



Here selector finds all matching ‘input’ elements then the element that have an attribute of ‘name’ and that also have the value ‘name’.

 

Get Elements by Hierarchy


Descendent Selector (“parent child”) – This will selects all descendent child elements of the parent including element which may a child, grandchild, great-grandchild, and so on, of that element.

Example:

<p><a href="http://google.com">Google</a></p>  
<div>  
<p> <a href="http://Yahoo.com">Yahoo!</a></p>  
<p><a href="http://gmail.com">Gmail</a></p>  
</div>  
<ul>
<li><a href="http://jquerymobile.com">jQuery Mobile</a></li>
</ul>
<div>
<ul>
<li><a href="http://jquery.com">jQuery</a></li>
<li><a href="http://jqueryui.com">jQuery UI</a></li>
</ul>
</div> 



When we write jQuery like:

$("div p");   



It will give us below result:

<p> <a href="http://Yahoo.com">Yahoo!</a></p>  
<p><a href="http://gmail.com">Gmail</a></p>  



And if we write like below code

$("div ul"); 



then it’s result will be like:

<ul>
<li><a href="http://jquery.com">jQuery</a></li>
<li><a href="http://jqueryui.com">jQuery UI</a></li>
</ul>



Child Selector (“parent > child”) – This may be used when you need to selects all direct child elements of the parent.
Example:

<p><a href="http://google.com">Google</a></p>  
<div>  
<p> <a href="http://Yahoo.com">Yahoo!</a></p>  
<p><a href="http://gmail.com">Gmail</a></p>  
</div>  
<ul>
<li><a href="http://jquerymobile.com">jQuery Mobile</a></li>
</ul>
<div>
<ul>
<li><a href="http://jquery.com">jQuery</a></li>
<li><a href="http://jqueryui.com">jQuery UI</a></li>
</ul>
</div> 



When we write jQuery like:

$("p > a");   



This will give us all the <a> tags:

<a href="http://google.com">Google</a>
<a href="http://Yahoo.com">Yahoo!</a></
<a href="http://gmail.com">Gmail</a> 



And below code will be resulted as:

$("li > a"); 



Result of above code will be

<a href="http://jquerymobile.com">jQuery Mobile</a>
<a href="http://jquery.com">jQuery</a>
<a href="http://jqueryui.com">jQuery UI</a> 



Get Elements by Filters

<!DOCTYPE html>
<html>
<head>
<title>Select Element by Selector Filter</title>
</head>
<body>
jQuery project sites:
<ul>
<li><a href="http://jquery.com">jQuery</a></li>
<li><a href="http://jqueryui.com">jQuery UI</a></li>
<li><a href="http://sizzlejs.com">Sizzle</a></li>
<li><a href="http://jquery.org">jQuery Project</a></li>
</ul>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script>
<script type="text/javascript">
//Select the element by attribute
alert($("a:first").attr("href")); // http://jquery.com
</script>
</body>
</html> 



There are three types of filter selectors that you can used to get elements: numerical or positioned filters, CSS filters and Pseudo filters

 


Numerical or positioned filters:


:first< matched first Gives –>

:last - Gives last matched element

:first-child – Gives the first child element

:last-child - Gives the last child element

:only-child - Gives all element that have no siblings

:nth-child(n) - Gives the nth child element

:nth-child(even|odd) – Gives the matched  even or odd children elements

:nth-child(xn+y) - Gives the nth matched children elements based on some formula.

:even - Gives even children elements

:odd - Gives odd children elements

:eq(n) - Gives nth position child element

:gt(n) - gives the children element those are greater than the nth position

:lt(n) - gives the children element those are less than the nth position

Traditional CSS filters:

:checked – It is basically used with checkboxes or radio buttons. It will return all checked elements.

:disabled – This will return all disabled elements

:enabled – This will give us all enabled elements

 

jQuery Pseudo filters:


:animated – Gives all elements with animations.

:button – Returns all button elements

:checkbox - Returns all checkbox elements

:contains(string) - Returns the elements those contain given string

Example:  $(“div:contains(Google)”)

:file – Return all file input elements

:has(selector) –Returns elements that have at least one of the specified matched selector.

:header - Returns header elements.

:hidden – Returns all hidden elements

:image - Returns image input elements

:input - Returns form elements

:parent - Returns elements that have children, including text, which are not empty

:password - Returns elements of type password

:radio - Returns radio elements

:reset - Returns reset buttons

:selected - Returns option elements in selected state

:submit - Returns elements of type submit

:text - Returns elements of type text

:visible - Returns elements that are visible

gridview add new row

In this post we will see how to add new row to grid. Gridview have a footer template. By default the visibility is false for this footer template . On add new row button click event, we will set the visibility of Gridview footer row to true and bind the grid again.

Aspx code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> 
<Columns> 
<asp:TemplateField HeaderText="ID"> 
<ItemTemplate> 
<asp:Label ID="lblID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"ID") %>'> 
</ItemTemplate> 
<FooterTemplate> 
 
</FooterTemplate> 

</asp:TemplateField> 
<asp:TemplateField HeaderText="First Name"> 
<ItemTemplate> 
<asp:Label ID="lblfirstName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"FirstName") %>'> 
</ItemTemplate> 
<FooterTemplate> 
<asp:TextBox ID="txtFirstName" runat="server"> 
</FooterTemplate> 
</asp:TemplateField> 
<asp:TemplateField HeaderText="Last Name"> 
<ItemTemplate> 
<asp:Label ID="lblLastName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"LastName") %>'> 
</ItemTemplate> 
<FooterTemplate> 
<asp:TextBox ID="txtLastName" runat="server"> 
</FooterTemplate> 
</asp:TemplateField> 
<asp:TemplateField HeaderText="Email"> 
<ItemTemplate> 
<asp:Label ID="lblEmail" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Email") %>'></asp:Label> 
</ItemTemplate> 
<FooterTemplate> 
<asp:TextBox ID="txtEmail" runat="server"> 
</FooterTemplate> 
</asp:TemplateField> 
<asp:TemplateField HeaderText="Check all"> 
<HeaderTemplate> 
<asp:CheckBox ID="CheckBox2" AutoPostBack="true" runat="server"  OnCheckedChanged="CheckBox2_CheckedChanged1" /> 
</HeaderTemplate> 
<ItemTemplate> 
<asp:CheckBox ID="CheckBox1"  runat="server" /> 
</ItemTemplate> 
<FooterTemplate> 
<asp:LinkButton ID="lnkSave" runat="server" CommandName="Save" OnClick="lnkSave_Click">Save 
</FooterTemplate> 
</asp:TemplateField> 
</Columns> 
</asp:GridView>



C# code behind
using System; 
using System.Data; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.HtmlControls; 

public partial class _Default : System.Web.UI.Page 
{ 
protected void Page_Load(object sender, EventArgs e) 
{ 
if (!Page.IsPostBack) 
{ 
BindGrid(); 
} 
} 
private void BindGrid() 
{ 
GridView1.DataSource = GridDataProvider.GetData(); 
GridView1.DataBind(); 
} 

protected void CheckBox2_CheckedChanged1(object sender, EventArgs e) 
{ 
foreach (GridViewRow r in GridView1.Rows) 
{ 
((CheckBox)r.FindControl("CheckBox1")).Checked = true; 
} 
} 
protected void Button1_Click(object sender, EventArgs e) 
{ 
} 
protected void Button2_Click(object sender, EventArgs e) 
{ 
GridView1.ShowFooter = true; 
BindGrid(); 
} 
protected void lnkSave_Click(object sender, EventArgs e) 
{ 
string ID = (  (TextBox)  GridView1.FooterRow.FindControl("txtID") ).Text ; 
string firstName = (  (TextBox)  GridView1.FooterRow.FindControl("txtFirstName") ).Text; 
// similarly you can find other controls and save 
} 





Vb.Net Code

Imports System 
Imports System.Data 
Imports System.Configuration 
Imports System.Web 
Imports System.Web.Security 
Imports System.Web.UI 
Imports System.Web.UI.WebControls 
Imports System.Web.UI.WebControls.WebParts 
Imports System.Web.UI.HtmlControls 
Public Partial Class _Default 
Inherits System.Web.UI.Page 
Protected Sub Page_Load(sender As Object, e As EventArgs) 
If Not Page.IsPostBack Then 
BindGrid() 
End If 
End Sub 
Private Sub BindGrid() 
GridView1.DataSource = GridDataProvider.GetData() 
GridView1.DataBind() 
End Sub 

Protected Sub CheckBox2_CheckedChanged1(sender As Object, e As EventArgs) 
For Each r As GridViewRow In GridView1.Rows 
(DirectCast(r.FindControl("CheckBox1"), CheckBox)).Checked = True 
Next 
End Sub 
Protected Sub Button1_Click(sender As Object, e As EventArgs) 
End Sub 
Protected Sub Button2_Click(sender As Object, e As EventArgs) 
GridView1.ShowFooter = True 
BindGrid() 
End Sub 
Protected Sub lnkSave_Click(sender As Object, e As EventArgs) 
Dim ID As String = (DirectCast(GridView1.FooterRow.FindControl("txtID"), TextBox)).Text 
Dim firstName As String = (DirectCast(GridView1.FooterRow.FindControl("txtFirstName"), TextBox)).Text 
' similarly you can find other controls and save 
End Sub 
End Class 

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

ASP.Net Authentication Modes

ASP.Net supports below authentication modes:
1. Windows
2. Forms
3. Passport
4. None

To enable authentication provider or mode we need to use authentication element from config file.
<system.web>
   <!-- mode=[Windows|Forms|Passport|None] -->
   <authentication mode="Windows" />
</system.web>
1.Windows:
  This is a default authentication mode in asp.net. This uses windows credentials for authentication. It relies on IIS to authenticate the user. Aftre authenticating the user it passes security token to asp.net. Windows authentication provides below ways:

Anonymous: IIS allows everybody to access asp.net application, no authentication is done.

Basic: User must have to provide username and password to get access to application. But username and password get sent over network in plain text format so it is bit insecure.

Digest: Same as Basic windows authentication but password is hashed before sending it over the netwrok and also user need to be use IE5 or later and windows accounts should stored in active directory.

Windows Integrated: User still need to provied username and password but it never sent over the network. Application either uses kerberos or challenge response protocol to authenticate the user. Kerberos provides tools for authentication and strong cryptography for secure communication.

2. Forms Authentication mode:  Forms authentication uses own customised HTML form to collect users credentials. Client or user directly sends credentials to asp.net application code for authenticatio. If application authenticates user it issues a cookie to ensure user is present on subsequent requests.

<!-- Web.config file -->
<system.web>
   <authentication mode="Forms">
      <forms forms="demoApp" loginUrl="/login.aspx" />
   </authentication>
</system.web>
 3. Passport Authentication: Passport authentication mode provides centralized authentication process provided by microsoft passport service. When user site registered with passport, the passport service grants site specific key.
<!-- Web.config file -->
<system.web>
   <authentication mode="Passport" />
</system.web>

ASP.Net Caching, Caching Concept

ASP.NET Caching:

Caching is process of storing frequently used data for reuse. Generally it stores data in memory becuase accessing data from memory is more efficient way rather that generate it again.

ASP.NET provides two types of catching:
1. Output Caching
2. Application Data Caching

Page Output Caching:
 Output caching is done with entire page or with the fragment/part of the page.
 a. Page Output Caching: ASP.Net allows caching entire contents of the page. This is good for caching static pages.

<%@ OutputCache Duration="60" VaryByParam="None" %>

Fragement/Pratial Page Caching:
  This is same as page output caching, but instead it uses to store part or fragment of the page in cache. This is done by caching user controls (.ascx) used in page.

<%@ OutputCache Duration="300" VaryByParam="*" Shared="true" %>

Here shared="true" is used to share same HTML if the user control is used in more than one pages, and to avoid caching same output/HTML of user control multiple time.

Application Data Caching: 

This is used to store data in cache like dataset or any collection objects, or any object that need to be cached:

Item can be added to cache using Cache.Insert(param, param) with expiration parameter. Also Item can be added to cache using Cache.add(param, param) with priority.

Data set can be added to cache like Cache["MyDataSet"] = MyDataSet; and retrived like ds = (DataSet) Cache["MyDataSet"].