Tuesday 7 May 2013

File handling in C#

File handling in C#

File handling is an unmanaged resource in your application system. It is outside your applicationdomain (unmanaged resource). It is not managed by CLR.

Data is stored in two ways, persistent and non-persistent manner.

When you open a file for reading or writing, it becomes stream.

Stream: Stream is a sequence of bytes traveling from a source to a destination over acommunication path.

The two basic streams are input and output streams. Input stream is used to read and output stream is used to write.

The System.IO namespace includes various classes for file handling.

The parent class of file processing is stream. Stream is an abstract class, which is used as the parent of the classes that actually implement the necessary operations.

The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.

Diagram to represent file-handling class hierarchy 
 
 file_handling.gif

Note: FileIno, DirectoryInfo and DriveInfo classes have instance methods. File, Directory, Path classes have static methods.

The following table describes some commonly used classes in the System.IO namespace.

Class Name
Description

FileStream

It is used to read from and write to any location within a file
BinaryReader
It is used to read primitive data types from a binary stream
BinaryWriter
It is used to write primitive data types in binary format
StreamReader
It is used to read characters from a byte Stream
StreamWriter
It is used to write characters to a stream.
StringReader
It is used to read from a string buffer
StringWriter
It is used to write into a string buffer
DirectoryInfo
It is used to perform operations on directories
FileInfo
It is used to perform operations on files

Reading and writing in the text file


StreamWriter Class


The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a writer, which can write a series of characters.

The following table describes some of the methods used by StreamWriter class.

Methods
Description
Close
Closes the current StreamWriter object and the underlying stream

Flush

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream

Write

Writes to the stream

WriteLine

Writes data specified by the overloaded parameters, followed by end of line

Program to write user input to a file using StreamWriter Class


using System;
using System.Text;
using System.IO;

namespace FileWriting_SW
{
    class Program
    {
        class FileWrite
        {
            public void WriteData()
            {
                FileStream fs = new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                Console.WriteLine("Enter the text which you want to write to the file");
                string str = Console.ReadLine();
                sw.WriteLine(str);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
        }
        static void Main(string[] args)
        {
            FileWrite wr = new FileWrite();
            wr.WriteData();
        }
    }
}

StreamReader Class


The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader, which can read series of characters.

The following table describes some methods of the StreamReader class.

Methods
Description
Close
Closes the object of StreamReader class and the underlying stream, and release any system resources associated with the reader
Peek
Returns the next available character but doesn't consume it
Read
Reads the next character or the next set of characters from the stream
ReadLine
Reads a line of characters from the current stream and returns data as a string
Seek
Allows the read/write position to be moved to any position with the file

Program to read from a file using StreamReader Class


using System;
using System.IO;

namespace FileReading_SR
{
    class Program
    {
        class FileRead
        {
            public void ReadData()
            {
                FileStream fs = new FileStream("c:\\test.txt", FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                Console.WriteLine("Program to show content of test file");
                sr.BaseStream.Seek(0, SeekOrigin.Begin);
                string str = sr.ReadLine();
                while (str != null)
                {
                    Console.WriteLine(str);
                    str = sr.ReadLine();
                }
                Console.ReadLine();
                sr.Close();
                fs.Close();
            }
        }
        static void Main(string[] args)
        {
            FileRead wr = new FileRead();
            wr.ReadData();

        }
    }
}

I hope that this article would have helped you in understanding file handling.

Wednesday 1 May 2013

Export Selected GridView Rows To Excel

http://rameshtalla.files.wordpress.com/2012/02/exportselectedgridviewrowstoexcel.png?w=511&h=309
In The Source Code:
<%@ Page Language=”C#” AutoEventWireup=”true”  EnableEventValidation=”false” EnableViewState=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title>Export GridView To Excel Example</title>
<link href=”StyleSheet.css” rel=”stylesheet” type=”text/css” />
<style type=”text/css”>
.style1
{
width: 55%;
}
.style2
{
width: 184px;
}
</style>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server” AllowPaging=”True”
DataSourceID=”sqlDataSourceGridView”
DataKeyNames=”CustomerID”
AutoGenerateColumns=”False”
onpageindexchanging=”GridView1_PageIndexChanging”
onrowdatabound=”GridView1_RowDataBound” CellPadding=”4″
ForeColor=”#333333″ GridLines=”None” >
<RowStyle BackColor=”#EFF3FB” />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID=”chkSelect” runat=”server” />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Customer ID”>
<ItemTemplate>
<asp:LinkButton ID=”lButton” runat=”server”
Text=’<%#Eval(“CustomerID”) %>’
PostBackUrl=”~/Default.aspx” >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”CompanyName” HeaderText=”Company”>
</asp:BoundField>
<asp:BoundField DataField=”ContactName” HeaderText=”Name”>
</asp:BoundField>
<asp:BoundField DataField=”City” HeaderText=”city”>
</asp:BoundField>
<asp:BoundField DataField=”Country” HeaderText=”Country” />
</Columns>
<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<EditRowStyle BackColor=”#2461BF” />
<AlternatingRowStyle BackColor=”White” />
</asp:GridView>
<asp:SqlDataSource ID=”sqlDataSourceGridView” runat=”server”
ConnectionString=”<%$ ConnectionStrings:northWindConnectionString %>”
SelectCommand=”SELECT [CustomerID], [CompanyName], [ContactName],
[City], [Country] FROM [Customers]“>
</asp:SqlDataSource>
<asp:Button ID=”btnExportToExcel” runat=”server”
Text=”Export To Excel”
onclick=”btnExportToExcel_Click”/>
</div>
</form>
</body>
</html>
In The Code Behind Window:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void FindCheckedRows()
{
ArrayList checkedRowsList;
if (ViewState["checkedRowsList"] != null)
{
checkedRowsList = (ArrayList)ViewState["checkedRowsList"];
}
else
{
checkedRowsList = new ArrayList();
}
foreach (GridViewRow gvRow in GridView1.Rows)
{
if (gvRow.RowType == DataControlRowType.DataRow)
{
string rowIndex = Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
CheckBox chkSelect = (CheckBox)gvRow.FindControl(“chkSelect”);
if ((chkSelect.Checked) && (!checkedRowsList.Contains(rowIndex)))
{
checkedRowsList.Add(rowIndex);
}
else if ((!chkSelect.Checked) && (checkedRowsList.Contains(rowIndex)))
{
checkedRowsList.Remove(rowIndex);
}
}
}
ViewState["checkedRowsList"] = checkedRowsList;
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
FindCheckedRows();
GridView1.ShowHeader = true;
GridView1.GridLines = GridLines.Both;
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Cells.RemoveAt(0);
if (ViewState["checkedRowsList"] != null)
{
ArrayList checkedRowsList = (ArrayList)ViewState["checkedRowsList"];
foreach (GridViewRow gvRow in GridView1.Rows)
{
gvRow.Visible = false;
if (gvRow.RowType == DataControlRowType.DataRow)
{
string rowIndex = Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
if(checkedRowsList.Contains(rowIndex))
{
gvRow.Visible = true;
gvRow.Cells[0].Visible = false;
}
}
}
}
ChangeControlsToValue(GridView1);
Response.ClearContent();
Response.AddHeader(“content-disposition”, “attachment; filename=GridViewToExcel.xls”);
Response.ContentType = “application/excel”;
StringWriter sWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
HtmlForm hForm = new HtmlForm();
GridView1.Parent.Controls.Add(hForm);
hForm.Attributes["runat"] = “server”;
hForm.Controls.Add(GridView1);
hForm.RenderControl(hTextWriter);
Response.Write(sWriter.ToString());
Response.End();
}
private void ChangeControlsToValue(Control gridView)
{
Literal literal = new Literal();
for (int i = 0; i < gridView.Controls.Count; i++)
{
if (gridView.Controls[i].GetType() == typeof(LinkButton))
{
literal.Text = (gridView.Controls[i] as LinkButton).Text;
gridView.Controls.Remove(gridView.Controls[i]);
gridView.Controls.AddAt(i,literal);
}
else if (gridView.Controls[i].GetType() == typeof(DropDownList))
{
literal.Text = (gridView.Controls[i] as DropDownList).SelectedItem.Text;
gridView.Controls.Remove(gridView.Controls[i]);
gridView.Controls.AddAt(i,literal);
}
else if (gridView.Controls[i].GetType() == typeof(CheckBox))
{
literal.Text = (gridView.Controls[i] as CheckBox).Checked ? “True” : “False”;
gridView.Controls.Remove(gridView.Controls[i]);
gridView.Controls.AddAt(i,literal);
}
if (gridView.Controls[i].HasControls())
{
ChangeControlsToValue(gridView.Controls[i]);
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
FindCheckedRows();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (ViewState["checkedRowsList"] != null)
{
ArrayList checkedRowsList = (ArrayList)ViewState["checkedRowsList"];
GridViewRow gvRow = e.Row;
if (gvRow.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = (CheckBox)gvRow.FindControl(“chkSelect”);
string rowIndex = Convert.ToString(GridView1.DataKeys[gvRow.RowIndex]["CustomerID"]);
if(checkedRowsList.Contains(rowIndex))
{
chkSelect.Checked = true;
}
}
}
}
}