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);
System.Console.WriteLine("There were {0} lines.", counter);

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.
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.

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");

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

class CreateNewFolder
 static void Main()
   // Create new Directory or folder on C:\ Drive.

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.

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");

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.
   <!-- mode=[Windows|Forms|Passport|None] -->
   <authentication mode="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 -->
   <authentication mode="Forms">
      <forms forms="demoApp" loginUrl="/login.aspx" />
 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 -->
   <authentication mode="Passport" />

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"].

ASP.NET Validation Controls

Below are types of asp.net validation controls:
1. Required FieldValidator
    Ensures user does not left control without data.
Reference:  How to: Validate Required Entries for ASP.NET Server Controls.

2. RangeValidator
   Check if entered values are in between given upper and lower boundries.
Reference:   How to: Validate Against a Range of Values for ASP.NET Server Controls.

3. RegularExpressionValidator
   Checks that entered data matches to the given pattern of Regular Expression.
Reference:  How to: Validate Against Patterns for ASP.NET Server Controls.

4. CompareValidator
    Compares the values entered by user with other control or constant value or
Reference: How to: Validate Against a Specific Value for ASP.NET Server Controls and How to: Validate Against a Data Type for ASP.NET Server Controls.

5. Custom Validator
   Check the entered values agains the logic you write yourself for validation.
Reference: How to: Validate with a Custom Function for ASP.NET Server Controls and How to: Validate Against Values in a Database for ASP.NET Server Controls.

ASP.Net Page life Cycle Events

Below are ASP.net Page life Cycle Events:

   We can use PreInit event to check IsPostBack property, if it is a new request or is it a postback. Also Master pages, Themes and profile values get set dynamically here. No control data ans control properties values from viewsate is loaded here.

   This event get raised after all controls get initialized. Use this event to read and initialize controls properties.

3.Init Complete
  Raised by Page object and used to complete all initialization.
   Use this event to do some process on the controls or page before loads event occures. This load viewstate data for page and itls all contrlos

   Page and it's all controls and controls child controlls totally get loaded during this event. Use this event to set the properties of the controls.

6.Control Events
    Use this event to handle specific controls event like button click event.

7.Load Ccomplete
   Use this event to do the tasks inorder to complete the page loading.

8. PreRender
   This event occure for every control on page and use this event to apply final changes to controls.

9.Save State complete
   This event performs the tasks that required to save view state.

   Page object call Render method of all the controls that writes the markup for each control.

  This event occures for page and its all controls. Use this event to do final work on page like closinf opened files, closing database connection..etc

ASP.Net Page Life Cycle

How page life cycle works in asp.net?
  • Page request:
            This is a stage before page life cycle starts. This step happens when user sends request for page. ASP.Net decides whether to parse and compile the requested page or just catched verions of page need to be send in response.
  • Start:
           In this step page request and response properties get set. Also page determines whether it is a page post back ot it is a new request and based on that sets IsPostBack() property value and also sets UICulture.
  • Page Initialization:
         In this step all the controls on page a available and each controls unique Id's get set. Also themes get set. But data is not loaded for the controls and control property values are not restored from viewstate.
  • Page load:
        In this step if request is a postback request then dat get loaded fro controls from viewstate and control state.
  • Validation:
        In this step Validate method of all valiation controls get called and it sets IsValid property of each individual validator control and of the page.
  • Postback event handling:
          If reuest is a postback, event handlers get called.
  • Rendering:
           In this step, page calls render method for each control and writes output to page response proerty. Before Rendering viewsate get saved for page and all it's controls.
  • Unload:
           This step happens when page and it's controls are fully loaded and sent to the client and ready to be discarded. Page properties like Response and Request are unloaded at this phase.

ASP.NET State management

    Whenever page is posted to the server, a new instance of the Web page class is created each time. This means that all information associated with the page and the controls on the page get lost with each round trip.
    To overcome this situation, ASP.NET provides various options to preserve the data. These are known as state management techniques:

Client-Side or Client-based State Management options:
·         View state
·         Control state
·         Hidden fields
·         Cookies
·         Query strings
View state, control state, hidden fields, cookies, and query strings all involve storing data on the client.
Server-side or Server-based State Management options:
·         Application state
·         Session state
·         Profile Properties
             application state, session state, and profile properties all store data in memory on the server.

While dealing with client-based options for state management it stores information either in the page or on the client computer.  Information is not maintained on the server between round trips.

View State

While page processing, the current state of the page and it’s all controls get hashed into a string and then saved in the form of hidden field on the page. If specified value in MaxPageStateFieldLength property get exceeds than the data to be stored then it get stored in multiple hidden fields.  When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.
Control State:
In order to persist or preserve the control data we can use control state option. For example,  we have a tab control that needs to be preserve selected tab in between post backs to server we can use control sate option..
We can use ViewState here, but it may possible that at page level ViewState is turned off.
The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property.

Hidden Fields:
  Hiddenfields are also used to store values on page. Hidden file does not render on page. Hiddenfield stores data in it's Value property. To make hiddenfield values available during page precoessing we need to submit the page using HTTP POST method or command. Hiddenfield values are not available using HTTP GET command.

 Cookie is nothing but the small amount of that is stored on client's browser using text file on client's file system on in memory.
Define and set value in cookie:
Response.Cookie["MyValue"].Value = "Test Value";
Get Cookie value

lblCookieText = Request.Cookies["MyValue"].Value;

Query String:
 Using Querystring application passes information or data by appending it to URL using question mark "?" like:

http://www.mywebsite.com?Name="Test Name"&phone="1234";

QueryString provides easy but 'limited' way to pass data from one page to other. To make querystring available during page processing, page must be submitted using HTTP GET command.

Application State:
   Application state provides way be store data which can be acessible globally in application. Application state uses System.Web.ApplicationState class.
    Defining and storing application state:
    Application["Name"] = "My Web";

// Accessing application variable value
string name;
if (Application["Name"] != null)
      name = Application["Name"].ToString();

Session State:
 Session state is way to store data in session variable for the current single browser session. If different users uses application , each users session state will be different.
Session State stroed in below three ways/ Session State Modes:

1. InProc: Means storing session in memory of the web server. It is the defualt session storage. InProc mode is high performant as it get read from same process. But it get affected by Worker process as both are in same process.

2. Stateserver: Storage location is server memeory with a seperate process, and not with the same process with asp.net worker process. This is less perfoamant process than InProc but it does not get affected in asp.net worker process get affected.

3.SQL Server:  Stores the data in SQL server database.