AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=305&pId=-1
Reading a Delimited File Using ASP.NET and VB.NET
page
by G Ajaykumar
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 41501/ 31

Introduction

We must be aware of importing data into a database, data which is used for importing are normally in the form of text file, some times these files are called a comma separated value file, which will normally have an extension .csv ,

In either of the files whether a text file or a .csv file all the values are delimited using a word or a letter or a number, this particular text which is used for separating the values is called a delimiter. This delimiter may be a word, a letter, a comma, a tab, or a space. Based on text which is used for separating the value, their respective file name goes on accordingly, for example if the values are delimited by comma (,) and the file may be called as comma delimited file, if the values are delimited using a delimiter hash (“#”) then that file may be referred to as a hash delimited file.

            Let us have a look of an example of what these delimited files look like.
Examples of Delimited Files

Example: Comma-delimited file

Value1, Value2, Value3, Value4, Value5

In the above example we can see a comma between the words Value1 Value2 until Value 5.

Example: TAB delimited file

Value1            Value2            Value3            Value4            Value5

In the above example we are able to see space between all the values.

We have seen how a delimited text file looks like; now let us have a look of other usage of delimited file.

 

  1. Data import into Database
  2. Used as a Database

Let us go in detail how these delimited files are used in both of the cases.

  1. Data import into Database

In a DBMS, RDBMS we create databases and tables, in a huge database with millions of records, in order to transfer data from one database or transport a database from one location to another, data is normally exported into a text file, when we try to export data to a text file, system will ask for a delimiter to be used for, when we specify the delimiter, the data’s stored in the fields will get appended with the delimiter, while importing the data back to the database, system will ask for the delimiter which is used, based on the delimiter, data gets imported into the database.

  1. Used as a database

In some areas where there is no support of database, delimited text files are used as a replacement for database with limited functionality, data’s are directly read from the delimited text file into arrays and manipulated.

Usually these types of delimited text files are used in the web applications, where hiring a database support with hosting is a costly affair, in order to get an act support like a database these delimited text files are used.

Reading a Delimited Text File

We have seen what a delimited text file is, what is the important usage and applications of these delimited text files. Now we shall go on and see how to read these delimited text files using ASP.NET and VB.NET

Note : delimiter’s sometimes are called a splitter

To read files using .NET we need to declare a namespace called SYSTEM.IO, which contains a set of classes, and methods, which is used for reading as well as writing files.

Let us now declare a name space, which will have System.IO

 

<%@Import Namespace="System.IO"%>

 

            Next we open the script tag, which will run at server, let us now open

the script tag ,we will be specifying our scripting language as vb in the tag

 

<Script language="vb" runat="server">

 

            Next we shall think about where to write the function, we shall write coding when the page loads, we shall declare the Subroutine, which fires when the page loads. Let us now declare the subroutine

 

            Sub page_load (Sender As Object,e As EventArgs)

 

We need to specify a file name which is to be read, whether it is a text file or a

. csv file, file name has to be assigned to a variable, let us now declare a

Variable named filetoread, which will be used to store the filename.

            Dim filetoread as string

Before we assign the file name to the variable, we will be using a server

Variable, which is used to trace the path of the specified file. Using

Server.mappath we can trace the absolute path of the file, which is specified.

            filetoread=server.mappath("readtest.txt")

In the above code we map the path of the text file readtest.txt where the path is

Stored into the variable filetoread.

Next we need to initiate the Stream Reader class, where we declare

filestream as a stream reader.

            Dim filestream as StreamReader

We need to assign a file to the streamreader to open the file,

            filestream = File.Opentext(filetoread)

In the above code we use Opentext method of the streamer and pass the variable filetoread, the variable filetoread contains the filepath.

Streamer reads the content, now we need a place to store the

Contents for the file, we will have to declare a variable named readcontents with Data type as string, which will store the contents of the file

            Dim readcontents as String

Using the ReadToEnd method of the streamer we read the entire contents of to the variable readcontents

 

readcontents = fileStream.ReadToEnd()

 

Now we will have to declare a variable, which will store the delimiter, that is the separator text, let us declare the variable named as textdelimiter with the data type as string.

 

Dim textdelimiter as String

 

Now the time has come for us to assign the delimiter, which might be a letter, word, number etc. Now let us assign the delimiter to be “geeyes”

 

Textdelimiter = "geeyes"

 

in the above code you can change the value of the variable textdelimiter as you wish, for example if you wish to change the delimiter to “#” your variable will look like this

 

Textdelimiter = “#” .

 

If you want to read a space delimited text file then you will need to provide a space between the double quotes of the variable as shown

 

Textdelimiter = “ “

 

Note: Value of variable is mandatory and is very important, as the reading of delimited file depends on value that is stored in the variable, which is the delimiter.

 

After we have specified the delimiter, now the time has come to split the contents of the files according to the delimiter, which has been specified. to do that first we shall declare a variable named splitout , then we will be using split function to split the text .

                                   

Dim splitout = Split(readcontents,textdelimiter)

   

In the above code we have declared a variable named splitout, to that variable we are assigning split functionality

Split (readcontents, textdelimiter)

 

Split function contains two parameters one is the content and the split text (delimiter).

In the above script we have readcontents variable, which contains the contents, then we pass the variable textdelimiter, which contains the delimiter text.

Passing two variables the contents are split according to the delimiter passed.

The split contents are stored in the form of arrays.

To exhibit the output we will be two asp: label whose text will be assigned dynamically

Let us place a label out of the </script> tag

 

<asp:label runat="server" id="lblsplittext">

 

Note: the above tag should be placed out of the </script> tag.

 

Now we declare a variable i with datatype as integer which is used for looping.

    dim i as integer

 

Now we will be using a for loop to read the contents which are stored in the arrays .

 

    for i=0 to Ubound(splitout)

 

in the above code Ubound(splitout) specifies the upper limit of the array splitout, splitout is the variable which contains the split text. Here you might wonder how splitout has become an array, when ever you use a split function the variable that is used for splitting is automatically converted into array. Here in our case splitout is automatically converted as an array.

 

Starting from zero which is our lower limit until the upper limit we write the text to the asp:label .

 

lblsplittext.Text &= "<b>Split </b>" & i+1 & ")   " & splitout(i)& "<br>"

 

in the above code lblsplittext.text , we dynamically assign the value to the asp:label named lblsplittext  let us have a look of the next part.

 

Here we use <b> bold tag which is a normal HTML tag, which is just used to brighten the test then we concatenate the variable i which is in loop , which displays serial number.

 

"<b>Split </b>" & i+1 & ")  

 

in the next part

 

" & splitout(i)& "<br>"

 

We are concatenating the variable splitout (i), we would see that variable i is passed to the splitout variable, here the concept of passing i is as follows,

we know that splitout is an array, the lower limit of and array start from zero, since this splitout(i) is within the loop, the variable passes from the lower limit to the upper limit, when it goes through loop it looks like, splitout(0), then splitout(1), then splitout(2) until the upper limit.

To navigate to the next array using the for loop then we use the key word

Next

 

In order to differentiate the file contents and the read delimited contents, we shall display the files contents to a asp: label directly which is raw without any split.

Now let us place the tag after the </script> tag

<asp:label runat="server" id="lblplaintext">

 

we dynamically assign the labels text with the contents read from the file.

 

lblplaintext.text = readcontents & "<br>"

  in the above code we concatenate a “<br>” just to break the line.

Now we close the stream class , to release the resources

filestream.Close()              

after we close the stream class we close the subroutine

End Sub

Next we close the script tag

</script>

After closing the script tag we will be placing the asp: label  as explained previously and some text.

<b>Plain Output</b><br />

<Asp: label runat="server" id="lblplaintext" Font-Name="Verdana" />

 

<b>Split Output</b><br />

<Asp: label runat="server" id="lblsplittext" Font-Name="Verdana" />

 

the above tags creates two asp: labels which is merely used for display purpose whose text are assigned dynamically.

 

That’s it…. We have gone through the complete procedure for reading a delimited text file.

Test Script

To test this script you will be creating two file one .aspx file and the other .txt file

 

  1. Open your notepad
  2. Copy the following complete code

 

<%--

 Beginning of script Reading a delimited text file written by G.Ajaykumar<ajaykumar_g AT hotmail.com>--%>

 

<%@Import Namespace="System.IO"%>

<script language="vb" runat="server">

Sub page_load(Sender As Object,e As EventArgs)

                                    Dim filetoread as string

                                    filetoread=server.mappath("readtest.txt")

                                    dim filestream as StreamReader

                                    filestream = File.Opentext(filetoread)

                                    Dim readcontents as String

                                    readcontents = fileStream.ReadToEnd()

                                    Dim textdelimiter as String

                                    textdelimiter = ","

                                    Dim splitout = Split(readcontents,textdelimiter)

                                    lblplaintext.text = readcontents & "<br>"

    dim i as integer

    for i=0 to Ubound(splitout)

                        lblsplittext.Text &= "<b>Split </b>" & i+1 & ")   " & splitout(i)& "<br>"

    next

   filestream.Close()                

End Sub

</script>

<asp:label align="center" ForeColor="Maroon" Font-Names="Arial" BackColor="LemonChiffon" BorderColor="#0000C0" runat="server" id="lbldisplay" Font-Name="Verdana" text="Reading a delimited text file using ASP.NET/VB.NET coded by G.Ajaykumar" /><br />

<br /><br /><b>Plain Output</b><br />

<asp:label runat="server" id="lblplaintext" Font-Name="Verdana" /><br />

<b>Split Output</b><br />

<asp:label runat="server" id="lblsplittext" Font-Name="Verdana" />

<%-- End of script--%>

 

Save the file as readdemilit.apx

 

  1. Now create a textfile named readtest.txt and copy the following text to that file and save it.

 

History of the world, is the history of few men who had faith in themselves, that faith calls out the divinity, with in, you can do anything you fail only when you do not strive sufficiently to manifest the infinite power, if you have faith in all the three hundred and thirty millions, of your mythological gods and in all the gods which foreign has now and gain faith, in yourselfs,what ever you hink that you will be if you think weak weak, you will be,if you think yourselves strong strong you will ,be free and hope for nothing from any one.

 

readlimit.aspx is the source file and readtest.txt is the delimited text file

 

dump these files to your wwwroot directory and run readlimit.aspx; that’s it!

 

Your output should look like the following

 

Plain Output
History of the world, is the history of few men who had faith in themselves, that faith calls out the divinity, with in, you can do anything you fail only when you do not strive sufficiently to manifest the infinite power, if you have faith in all the three hundred and thirty millions, of your mythological gods and in all the gods which foreign has now and gain faith, in yourselfs,what ever you hink that you will be if you think weak weak, you will be,if you think yourselves strong strong you will ,be free and hope for nothing from any one.

Delimited Output
Split 1) History of the world
Split 2) is the history of few men who had faith in themselves
Split 3) that faith calls out the divinity
Split 4) with in
Split 5) you can do anything you fail only when you do not strive sufficiently to manifest the infinite power
Split 6) if you have faith in all the three hundred and thirty millions
Split 7) of your mythological gods and in all the gods which foreign has now and gain faith
Split 8) in yourselfs
Split 9) what ever you hink that you will be if you think weak weak
Split 10) you will be
Split 11) if you think yourselves strong strong you will
Split 12) be free and hope for nothing from any one.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 7:18:32 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search