Saturday, April 5, 2014

Read a Text file line by line in C# .NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>Read txt file</h2>
    <asp:Label ID="Label1" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class Default7 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ReadLineByLine();
        ReadTextFileAndSplit();
    }
    void ReadLineByLine()
    {
        string inputString;
        using (StreamReader streamReader = File.OpenText(Server.MapPath("~") + @"\test.txt"))
        {
            inputString = streamReader.ReadLine();
            while (inputString != null)
            {
                Label1.Text += inputString + "<br \\>";
                inputString = streamReader.ReadLine();
            }
        }
    }
    void ReadTextFileAndSplit()
    {
        string inputString;
        using (StreamReader streamReader = File.OpenText(Server.MapPath("~") + @"\test.txt"))
        {
            inputString = streamReader.ReadLine();
            while (inputString != null)
            {
                string[] spilt = inputString.Split(' ');
                string Name = spilt[0];
                string Location = spilt[1];
                string Id = spilt[2];
                inputString = streamReader.ReadLine();
            }
        }
    }
}


test.txt
Rakesh NY 101
Ram Canada 102
Suresh India 103

0 comments:

Post a Comment