Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
 Thursday, April 17, 2008

I know Joel and Jeff are ready. I am ready! Are you?

http://www.stackoverflow.com/

Thursday, April 17, 2008 10:09:41 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
Tech News and Issues

In my previous article I showed you how to add a web service reference in your ASP.NET application, call a webmethod and the display the values returned byt the web service to a Label. This time I'm going to show you how to transform that Xml string into a DataSet.

I suggest that you read the previous article before continuing in reading this post so you'll have a better insight on what we are trying to accomplish on this article.

Let's begin!

To start off this article let's look at how the application that we built for the previous article.

and the HTML code for the UI

<%@ Page Language="C#" AutoEventWireup="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">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Keith Rull's Consuming Web Services Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <strong>Symbol</strong><br />
            <asp:TextBox ID="symbolTextBox" 
                         runat="server" />
            <asp:Button ID="executeButton" 
                        runat="server" 
                        Text="Execute"
                        OnClick="executeButton_Click" />
            <br />
            <br />
            <strong>Result</strong>
            <br />
            <asp:Label ID="xmlResultLabel" 
                        runat="server" />
        </div>
    </form>
</body>
</html>

and the underlying code for the click event of the "Execute" button

    protected void executeButton_Click(object sender, EventArgs e)
    {
        //get the execution symbol entered in the TextBox
        string executionSymbol = symbolTextBox.Text;

        //get the stock quote information
        string quoteInfo = GetStockQuoteInformation(executionSymbol);

        //HtmlEncode the string to properly render it on the page
        string htmlEncodedResult = System.Web.HttpUtility.HtmlEncode(quoteInfo);
       
        //assign the HtmlEncoded string to our Label control
        xmlResultLabel.Text = htmlEncodedResult;
    }

As you can see the code above does the job of displaying the retuned xml from the webservice. It works. We can understand that XML because we are techie enough but imagine a normal user seeing a xml values on his screen? Yup. Not good. The best way to present data to a user is to show values in tabular form. A lot more pleasing to the eyes and much easier to understand. With that said let's start by replacing the Label control in the form with a DetailsView control. The new aspx page for our form should look like this:

<%@ Page Language="C#" AutoEventWireup="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">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Keith Rull's Consuming Web Services Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <strong>Symbol</strong><br />
            <asp:TextBox ID="symbolTextBox" 
                         runat="server" />
            <asp:Button ID="executeButton" 
                        runat="server" 
                        Text="Execute"
                        OnClick="executeButton_Click" />
            <br />
            <br />
            <strong>Result</strong>&nbsp;<br />
            <asp:DetailsView ID="stockQuoteInfoDetailsView" runat="server" Height="50px" Width="125px">
            </asp:DetailsView>
        </div>
    </form>
</body>
</html>

As you can see in the old code for the Click event we are able to get the XML and display it on a Label. What we need to do now is to read that XML string and assign it to a our DetailsView but there is one problem... The XML string needs to be converted to an object that supports IList or IEnumerable first before it could be loaded to our DetailsView.

To solve this problem I've decided to create this method that accepts an XML string and converts it to a DataSet.

    /// <summary>
    /// A function that takes an XML string and converts it into a DataSet
    /// </summary>
    /// <param name="xmlString">The xml string to tranform into a DataSet</param>
    /// <returns>The DataSet representing the values and schema from our xml string</returns>
    private DataSet XmlString2DataSet(string xmlString)
    {
        //create a new DataSet that will hold our values
        DataSet quoteDataSet = null;

        //check if the xmlString is not blank
        if (String.IsNullOrEmpty(xmlString)) {
            //stop the processing
            return quoteDataSet;
        }

        try{
            //create a StringReader object to read our xml string
            using (StringReader stringReader = new StringReader(xmlString))
            {
                //initialize our DataSet
                quoteDataSet = new DataSet();

                //load the StringReader to our DataSet
                quoteDataSet.ReadXml(stringReader);
            }
        }
        catch{
            //return null
            quoteDataSet = null;
        }

        //return the DataSet containing the stock information
        return quoteDataSet;
    }

Now we can modify our our executeButton_Click event

    protected void executeButton_Click(object sender, EventArgs e)
    {
        //get the execution symbol entered in the TextBox
        string executionSymbol = symbolTextBox.Text;

        //get the stock quote information
        string quoteInfo = GetStockQuoteInformation(executionSymbol);

        //create our quote DataTable
        DataSet quoteDataSet = XmlString2DataSet(quoteInfo);

        //assign the quote information to our DetailsView
        stockQuoteInfoDetailsView.DataSource = quoteDataSet;
        stockQuoteInfoDetailsView.DataBind();
    }

All we did was pass the xml string to the XmlString2DataSet function to retrieve a DataSet containing the stock quote information and then assigning that DataSet object to our DetailsView for display. Below is how the final form looks-like after our modification

Now that is more presentable! I hope I was able to share with you something useful. Next stop, we'll be building Master-Detail pages in ASP.NET ;)

Care for the code? Grab it here: KeithRull.ConsumingWebServices.Part2.zip (5.76 KB)

Thursday, April 17, 2008 5:27:06 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | ASP.NET | Tutorial
 Friday, April 11, 2008

I saw this comment on Dustin Campbell's MVP renewal post and it made me smile

That is definetely one proud mama! Congrats Dustin and Happy Birthday too ;)

Friday, April 11, 2008 3:51:16 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
All about Keith | Tech News and Issues
 Tuesday, April 08, 2008

I've been meaning to write this tutorial for a month now and finally i found time to write it. As you may have noticed, I have been blogging about accessing files (here, here and here), reading XML, and loading XML data to a GridView lately. The reason behind this is that I am preping you guys up for a much larger article that would span to 5 articles with different demos for each post... something that needs to spend a little bit of time on the lower end of the grid to make the whole thing easier to explain once we start building the big picture... but I won't spill the details about the post yet ;) so better keep up with the site to learn what I've been brewing since early March.

In the meantime let's talk about how to consume XML Web Services in ASP.NET. I don't want to bore you with explanations on what an XML Web Service means so I'll just lead you to a document written by Roger Wolter in 2001 that explains the whole enselada about Web Services. Below is an excerpt from that document:

XML Web services are the fundamental building blocks in the move to distributed computing on the Internet. Open standards and the focus on communication and collaboration among people and applications have created an environment where XML Web services are becoming the platform for application integration. Applications are constructed using multiple XML Web services from various sources that work together regardless of where they reside or how they were implemented.

There are probably as many definitions of XML Web Service as there are companies building them, but almost all definitions have these things in common:

  • XML Web Services expose useful functionality to Web users through a standard Web protocol. In most cases, the protocol used is SOAP.
  • XML Web services provide a way to describe their interfaces in enough detail to allow a user to build a client application to talk to them. This description is usually provided in an XML document called a Web Services Description Language (WSDL) document.
  • XML Web services are registered so that potential users can find them easily. This is done with Universal Discovery Description and Integration (UDDI).

Now that we have nailed the basic definition let's build a simple application that consumes a publicly available web service. There are a lot of sites that list useful public web services and one of those sites is WebServiceX. WebServiceX's website contains 70+ freely available web service that you can use and utilize in your projects. For this demo I've decided to use the StockQuote service which is a web service that allows you to query stock information by using the symbol of the stock. Here's some information about the service taken from their website:

Summary: Get Stock quote for a company symbol by using this web service
Endpoint:
http://www.webservicex.net/stockquote.asmx
Disco: http://www.webservicex.net/stockquote.asmx?Disco
WSDL Location: http://www.webservicex.net/stockquote.asmx?wsdl

Let's begin building!

First, let's start by creating a new ASP.NET Website Project

Once that's done we need to add a Web Reference to our project that would point to the StockQuote service hosted on the WebServiceX website. We can do this by right-clicking on our solution and then selecting the Web Reference menu item.

A new screen will appear that will enable you to specify the URL of the web service. Input http://www.webservicex.net/stockquote.asmx on the URL dropdownlist to create reference to the StockQuote service.

Click "Add Reference" to add the reference to the project. You'll notice that the folder structure of your project has been updated and a new folder called "App_WebReferences" has been added to the project.

Ok, now let's build our UI. My idea for this sample application is to have a TextBox that allows users to enter the symbol, a Button control that will trigger the lookup to the web service via it's Click event and a Label control that will used to display the values returned by the web service. Below is how I envisioned our form to look-like:

And here's the accompanying HTML source for our form

<%@ Page Language="C#" AutoEventWireup="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">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Keith Rull's Consuming Web Services Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <strong>Symbol</strong><br />
            <asp:TextBox ID="symbolTextBox" 
                         runat="server" />
            <asp:Button ID="executeButton" 
                        runat="server" 
                        Text="Execute"
                        OnClick="executeButton_Click" />
            <br />
            <br />
            <strong>Result</strong>
            <br />
            <asp:Label ID="xmlResultLabel" 
                        runat="server" />
        </div>
    </form>
</body>
</html>

Now that we have the infrastructure in place it's time to write some code. The first thing that we need to do on the code-behind level is to add the using declaration to include the web service class in our page.

This enables us to create objects from our web service. The class that we would be using in this exercise is the StockQuote object which has the StockQuote.GetQuote method that returns the XML data containing the information for a specified symbol. Below is the method I wrote to show you how to use this class:

    /// <summary>
    /// A function that retrieves the stock information
    /// from the StockQuote web service
    /// </summary>
    /// <param name="executionSymbol">the execution symbol to lookup</param>
    /// <returns>The string containing the XML information regarding the symbol</returns>
    private string GetStockQuoteInformation(string executionSymbol)
    {
        string quoteInfo = String.Empty;

        //check if the executionSymbol is not blank
        if (String.IsNullOrEmpty(executionSymbol)) {
            //stop the processing
            return quoteInfo;
        }

        try
        {
            //create a StockQuote object
            StockQuote quote = new StockQuote();

            //get the stock quote information for the specified symbol
            quoteInfo = quote.GetQuote(executionSymbol);
        }
        catch (Exception ex) {
            //raise the error
            string errorMessage = String.Format("Error while trying to connect to the Web Service. {0}", ex.Message);
            throw new Exception(errorMessage);
        }

        //return the quote information
        return quoteInfo;
    }

Now that we have the function that will call our web service it's time to hook up our method to the Click event of our button.

    protected void executeButton_Click(object sender, EventArgs e)
    {
        //get the execution symbol entered in the TextBox
        string executionSymbol = symbolTextBox.Text;

        //get the stock quote information
        string quoteInfo = GetStockQuoteInformation(executionSymbol);

        //HtmlEncode the string to properly render it on the page
        string htmlEncodedResult = System.Web.HttpUtility.HtmlEncode(quoteInfo);
        
        //assign the HtmlEncoded string to our Label control
        xmlResultLabel.Text = htmlEncodedResult;
    }

As you can see the whole process was built with little code. Run the application and see how the easy it is to connect to a web service, call a web service method and use it's returned value.

I hope you learned something from this tutorial. On our next article i'll show you howto display the XML returned by the web service to a GridView.

Later ;)

Tuesday, April 08, 2008 4:48:30 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET
 Tuesday, April 01, 2008

Last week I showed you how to read an XML file, load it to a DataSet and assign those values into a GridView. Today I'll show you how you can read an XML file using the XmlDataSource object.

Let's assume that we have an XML file called Symbols.xml in our App_Data folder

that contains the following data

<?xml version="1.0" encoding="utf-8" ?>
<Symbols>
    <Symbol ExecutionSymbol="ATT" Name="AT&amp;T"></Symbol>
    <Symbol ExecutionSymbol="MSFT" Name="Microsoft"></Symbol>
    <Symbol ExecutionSymbol="GOOG" Name="Google"></Symbol>
    <Symbol ExecutionSymbol="CSCO" Name="Cisco"></Symbol>
    <Symbol ExecutionSymbol="IP" Name="International Paper Co."></Symbol>
    <Symbol ExecutionSymbol="MF" Name="MF Global"></Symbol>
    <Symbol ExecutionSymbol="Q" Name="Qwest Communications International Inc."></Symbol>
    <Symbol ExecutionSymbol="BMC" Name="BMC Software Inc."></Symbol>
    <Symbol ExecutionSymbol="WCI" Name="WCI Communities Inc."></Symbol>
    <Symbol ExecutionSymbol="SPY" Name="SDRs"></Symbol>
    <Symbol ExecutionSymbol="LEH" Name="Lehman Brothers Holdings Inc."></Symbol>
    <Symbol ExecutionSymbol="XLF" Name="Financial Select Sector SPDR"></Symbol>
    <Symbol ExecutionSymbol="QQQQ" Name="PowerShares QQQ TR 1"></Symbol>
    <Symbol ExecutionSymbol="IWM" Name="IShare Rus 2000 INDX"></Symbol>
    <Symbol ExecutionSymbol="GE" Name="General Electric Co."></Symbol>
    <Symbol ExecutionSymbol="MER" Name="Merrill Lynch Co., Inc."></Symbol>
    <Symbol ExecutionSymbol="BAC" Name="Bank of America Corporation"></Symbol>
    <Symbol ExecutionSymbol="INTC" Name="Intel Corp"></Symbol>
    <Symbol ExecutionSymbol="F" Name="Ford Motor Co."></Symbol>
    <Symbol ExecutionSymbol="QID" Name="UltraShort QQQ ProShares"></Symbol>
</Symbols>

and we want to load it to a GridView with no server-side code and a quick and easy way. The answer is to use the XmlDataSource object. The XmlDataSource control is an ASP.NET control that allows you to automatically read XML Data and make that data readily available to any ASP.NET control.

To start using this control, go to your Toolbox and drag the XmlDataSource control to your page.

Once the control is on the page it would popup a dialog that has configuration options for our XmlDataSource control. Click the "Configure Data Source" button to configure our XmlDataSource

A popup like below will come up that allows you to select the Xml file you want to your XmlDataSource object to read. It also gives you the option to select the XSL file. You can also specify an XPath expression to use to filter the data in our Xml.

Click the "Browse" button for the "Data File" option to select an XML file.

A new dialog will appear that will let you navigate the folder tree to select your desired XML file

Click "Ok" and you'll be taken back to the "Configure Data Source" screen. Click "Ok" again to finalize the XML data assignment.

Now that we have the file set in to our XmlDataSource control we need assign it to a control. We can do that by dragging a GridView control to our form.

Next, we need to assign the XmlDataSource control as the data source for our GridView. We can do this by selecting our XmlDataSource from the "Choose Data Source" dropdownlist.

Click "XmlDataSource1" and you will notice that our GridView was automatically updated and now shows the contents of our XML file.

Easy huh? Next up, Consuming Web Services in ASP.NET

 

Monday, March 31, 2008 11:15:13 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | ASP.NET | Tutorial
 Thursday, March 27, 2008

Last week I showed you ways on how to read text files. This time around we will be looking at how to load XML files into a DataSet.

Let's assume that we have a file called Symbols.xml which contains some XML data.

<?xml version="1.0" encoding="utf-8" ?>
<Symbols>
    <Symbol ExecutionSymbol="ATT" Name="AT&amp;T"></Symbol>
    <Symbol ExecutionSymbol="MSFT" Name="Microsoft"></Symbol>
    <Symbol ExecutionSymbol="GOOG" Name="Google"></Symbol>
    <Symbol ExecutionSymbol="CSCO" Name="Cisco"></Symbol>
    <Symbol ExecutionSymbol="IP" Name="International Paper Co."></Symbol>
    <Symbol ExecutionSymbol="MF" Name="MF Global"></Symbol>
    <Symbol ExecutionSymbol="Q" Name="Qwest Communications International Inc."></Symbol>
    <Symbol ExecutionSymbol="BMC" Name="BMC Software Inc."></Symbol>
    <Symbol ExecutionSymbol="WCI" Name="WCI Communities Inc."></Symbol>
    <Symbol ExecutionSymbol="SPY" Name="SDRs"></Symbol>
    <Symbol ExecutionSymbol="LEH" Name="Lehman Brothers Holdings Inc."></Symbol>
    <Symbol ExecutionSymbol="XLF" Name="Financial Select Sector SPDR"></Symbol>
    <Symbol ExecutionSymbol="QQQQ" Name="PowerShares QQQ TR 1"></Symbol>
    <Symbol ExecutionSymbol="IWM" Name="IShare Rus 2000 INDX"></Symbol>
    <Symbol ExecutionSymbol="GE" Name="General Electric Co."></Symbol>
    <Symbol ExecutionSymbol="MER" Name="Merrill Lynch Co., Inc."></Symbol>
    <Symbol ExecutionSymbol="BAC" Name="Bank of America Corporation"></Symbol>
    <Symbol ExecutionSymbol="INTC" Name="Intel Corp"></Symbol>
    <Symbol ExecutionSymbol="F" Name="Ford Motor Co."></Symbol>
    <Symbol ExecutionSymbol="QID" Name="UltraShort QQQ ProShares"></Symbol>
</Symbols>

And you want to load that data into a DataSet and display it to a GridView. How would you do it?

There are different ways you can load an XML file to a DataSet and i'm here to show you 4 of them. I don't have alot of time to explain the intrinsicts of each sample or performance comparisson of each technique because of time constraints so i'll leave that part for you to figure out the best among this examples. ;)

SAMPLE 1

//Sample 1
//the code below shows us how to load the XML document
//directly to our dataset by just specifying the file
//location to the DataSet.ReadXml method of the DataSet

using System;
using System.Data;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath(@"App_Data/Symbols.xml");

        if (File.Exists(xmlFilePath))
        {
            //create the Dataset object
            using (DataSet ds = new DataSet())
            {
                //load the xml data to the dataset
                ds.ReadXml(xmlFilePath);

                //bind the values to our GridView
                symbolGridView.Caption = "<h4>Loaded the data using Sample1</h4>";
                symbolGridView.DataSource = ds;
                symbolGridView.DataBind();
            }
        }
    }
}

SAMPLE 2

//Sample 2
//The code below is using the TextReader object to read
//the contents of the file and then assign those values
//to our dataset object

using System;
using System.Data;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath(@"App_Data/Symbols.xml");

        if (File.Exists(xmlFilePath))
        {
            //Create the TextReader object
            using (TextReader sReader = new StreamReader(xmlFilePath))
            {
                //create the Dataset object
                using (DataSet ds = new DataSet())
                {
                    //load the xml data from the TextReader to the Dataset
                    ds.ReadXml(sReader);

                    //bind the values to our GridView
                    symbolGridView.Caption = "<h4>Loaded the data using Sample2</h4>";
                    symbolGridView.DataSource = ds;
                    symbolGridView.DataBind();
                }
            }
        }
    }
}

SAMPLE 3

//Sample 3
//The code below is basically the same as the above code
//but this time we are using the XmlTextReader object
//instead of using the TextReader object. Please note that
//the XmlReader object calls the TextReader internally.

using System;
using System.Data;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath(@"App_Data/Symbols.xml");

        if (File.Exists(xmlFilePath))
        {
            //Create the XmlTextReader object
            using (XmlTextReader xTextReader = new XmlTextReader(xmlFilePath))
            {
                //create the Dataset object
                using (DataSet ds = new DataSet())
                {
                    //load the xml data to dataset
                    ds.ReadXml(xTextReader);

                    //bind the values to our GridView
                    symbolGridView.Caption = "<h4>Loaded the data using Sample3</h4>";
                    symbolGridView.DataSource = ds;
                    symbolGridView.DataBind();
                }
            }
        }
    }
}

SAMPLE 4

//Sample 4
//The code below uses an XmlDocument object and reads a file
//using the XmlDocument.LoadXml method. That data is then
//transfered to a DataSet by using the DataSet.ReadXml method
//and passing a XmlNodeReader object based on our XmlDocument

using System;
using System.Data;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath(@"App_Data/Symbols.xml");

        if (File.Exists(xmlFilePath))
        {
            //Create the Dataset object
            using (DataSet ds = new DataSet())
            {
                //create the XmlDocument object
                XmlDocument xDoc = new XmlDocument();

                //load the contents of the file to our XmlDocument object
                xDoc.LoadXml(File.ReadAllText(xmlFilePath));

                //load the xml data in the XmlDocument object to the Dataset
                ds.ReadXml(new XmlNodeReader(xDoc));

                //bind the values to our GridView
                symbolGridView4.Caption = "<h4>Loaded the data using Sample4</h4>";
                symbolGridView4.DataSource = ds;
                symbolGridView4.DataBind();
            }
        }
    }
}

And that's it. On my next post i'll show you how to load XML data directly to the GridView using the XMLDataSource object.

HTH.

Thursday, March 27, 2008 3:47:22 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Tutorial
 Wednesday, March 19, 2008

Sample 3 is similar to Sample 1 and and Sample 2 but it uses the File.ReadAllText method which reads the content of the whole file instead of reading the data line by line or reading the data and putting the values into a string[].

[C# Version]

using System;
using System.IO;

namespace KeithRull.ReadMyFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //the filename of the file to read
            string xmlFilename = "Symbols.xml";
          
            //validate if the file exist
            if (File.Exists(xmlFilename))
            {
                //read the contents of the file
                string fileContent = File.ReadAllText(xmlFilename);

                //display the output in the screen
                Console.WriteLine(fileContent);
            }
            else
            {
                //notify that the file was not found
                Console.WriteLine("File not found!");
            }

            //pause and wait for the user.
            Console.ReadLine();
        }
    }
}

[VB.NET Version]

Imports System 
Imports System.IO 

Namespace KeithRull.ReadMyFile 
    Class Program 
        Private Shared Sub Main(ByVal args As String()) 
            'the filename of the file to read 
            Dim xmlFilename As String = "Symbols.xml" 
            
            'validate if the file exist 
            If File.Exists(xmlFilename) Then 
                'read the contents of the file 
                Dim fileContent As String = File.ReadAllText(xmlFilename) 
                
                'display the output in the screen 
                Console.WriteLine(fileContent) 
            Else 
                'notify that the file was not found 
                Console.WriteLine("File not found!") 
            End If 
            
            'pause and wait for the user. 
            Console.ReadLine() 
        End Sub 
    End Class 
End Namespace 
Wednesday, March 19, 2008 7:18:14 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Tutorial
Sample demonstrates how to use the File.ReadAllLines technique 

[C# Version]

using System;
using System.IO;

namespace KeithRull.ReadMyFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //the filename of the file to read
            string xmlFilename = "Symbols.xml";
          
            //validate if the file exist
            if (File.Exists(xmlFilename))
            {
                //read the contents of the file
                string[] fileContent = File.ReadAllLines(xmlFilename);

                //iterate for each line item in our file
                foreach (string lineItem in fileContent)
                {
                    //display the output in the screen
                    Console.WriteLine(lineItem);
                }
            }
            else
            {
                //notify that the file was not found
                Console.WriteLine("File not found!");
            }

            //pause and wait for the user.
            Console.ReadLine();
        }
    }
}

[VB.NET Version]

Imports System
Imports System.IO

Namespace KeithRull.ReadMyFile
    Class Program
        Private Shared Sub Main(ByVal args As String())
            'the filename of the file to read
            Dim xmlFilename As String = "Symbols.xml"
           
            'validate if the file exist
            If File.Exists(xmlFilename) Then
                'read the contents of the file
                Dim fileContent As String() = File.ReadAllLines(xmlFilename)
               
                'iterate for each line item in our file
                For Each lineItem As String In fileContent
                    'display the output in the screen
                    Console.WriteLine(lineItem)
                Next
            Else
                'notify that the file was not found
                Console.WriteLine("File not found!")
            End If
           
            'pause and wait for the user.
            Console.ReadLine()
        End Sub
    End Class
End Namespace

Wednesday, March 19, 2008 7:04:44 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Tutorial

Sample 1 demonstrates how to use the StreamReader technique when reading the contents of a file

[C# Version]

using System;
using System.IO;

namespace KeithRull.ReadMyFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //the filename of the file to read
            string xmlFilename = "Symbols.xml";
          
            //validate if the file exist
            if (File.Exists(xmlFilename))
            {
                //create a new StreamReader object tha would read the file
                using (StreamReader sReader = new StreamReader(xmlFilename))
                {
                    //create a string object that would hold the
                    //value of each line in our file
                    string line = String.Empty;
                    
                    //iterate for each line item in our file
                    while ((line = sReader.ReadLine()) != null)
                    {
                        //display the output in the screen
                        Console.WriteLine(line);
                    }
                }
            }
            else
            {
                //notify that the file was not found
                Console.WriteLine("File not found!");
            }

            //pause and wait for the user.
            Console.ReadLine();
        }
    }
}

[VB.NET Version]

Imports System 
Imports System.IO 

Namespace KeithRull.ReadMyFile 
    Class Program 
        Private Shared Sub Main(ByVal args As String()) 
            'the filename of the file to read 
            Dim xmlFilename As String = "Symbols.xml" 
            
            'validate if the file exist 
            If File.Exists(xmlFilename) Then 
                'create a new StreamReader object tha would read the file 
                Using sReader As New StreamReader(xmlFilename) 
                    'create a string object that would hold the 
                    'value of each line in our file 
                    Dim line As String = [String].Empty 
                    
                    'iterate for each line item in our file 
                    While (line = sReader.ReadLine()) IsNot Nothing 
                        'display the output in the screen 
                        Console.WriteLine(line) 
                    End While 
                End Using 
            Else 
                'notify that the file was not found 
                Console.WriteLine("File not found!") 
            End If 
            
            'pause and wait for the user. 
            Console.ReadLine() 
        End Sub 
    End Class 
End Namespace 
Wednesday, March 19, 2008 6:52:53 PM (GMT Standard Time, UTC+00:00)  #