Lost Password?


  #1 (permalink)  
Old 02-25-2008, 07:35 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 9,224
Last Blog:
Ext JS or Ext GWT
Rep Power: 20
Jordan is just really niceJordan is just really niceJordan is just really niceJordan is just really nice
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Visual Studio 2008: C# Reading Files

In this tutorial I will show you how to read files using Visual Studio 2008 C#.

The TextReader Class (from MSDN)
TextReader is the abstract base class of StreamReader and StringReader, which read characters from streams and strings, respectively. Use these derived classes to open a text file for reading a specified range of characters, or to create a reader based on an existing stream.

Getting Started
1) Open Visual Studio 2008 and create a new Console Application using Visual C#. I've named my project ccFileRead but you can name as you like. We will be using a Console Application in order to eliminate confusion with GUI objects. This tutorial is intended to show you how to read a file.



2) Click "Start/Run" and type "notepad", press enter. We will create a txt file to read in this step. Type in several names pressing enter after each name. I used Luke, John, Jerry, Winged, TcM, Jordan. This file is also attached at the bottom of this thread. Once you have entered the names click "File/Save As". Click "My Computer" on the left hand side of the Save As dialog. Double click "Local Disk (C:)". Type "UserNames.txt" as the "File Name:" in the bottom of the dialog. Click Save.



3) Close the text file and switch back to Visual Studio 2008. You should see the default Console Application code generated by C#.

C# Code:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ccFileRead
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.         }
  13.     }
  14. }



Reading a Text File
The TextReader is in the System.IO namespace. The first thing you should do is add this line to the top of your program:

Code:
using System.IO;
directly under:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Now you will be able to use the entire IO namespace without typing out the full name. Next we want to create a string and assign it the path/name of our file:

Code:
// Assign the filename
string fileName = "c:\\UserNames.txt";
Add this in the "static void Main(string[] args)" function (between the { and }). The double blackslash is required to assert a single backslash. This is because a single backslash key is defined as the escape character.

Creating the TextReader
The TextReader is defined by creating a new StreamReader and passing the file path/name to it. StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.

StreamReader defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system.

Thus you have:

Code:
// Create reader & open file
TextReader textReader = new StreamReader(fileName);
Add this directly below the fileName string you set earlier.

Reading the File
Reading the file with a TextReader is incredibly simple. There are two methods for reading the file: ReadLine and ReadToEnd. As you may have guessed the ReadLine() method reads only one line. The ReadToEnd() reads the entire file. Since we have multiple names on different lines we need to use the ReadToEnd(). We also want to display this information to the user and print the TextReader Type (using the GetType().Name property). Add this line below the previous:

Code:
// Read text to end of file
Console.WriteLine("Reading {0} - {1}", 
textReader.GetType().Name, textReader.ReadToEnd());
Closing the Stream
Once you are done using your file streams it is important to close them. This frees up the file and memory. Added:

Code:
// close the stream
textReader.Close();
Final Code
Your code should look like this:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ccFileRead
{
    class Program
    {
        static void Main(string[] args)
        {
            // Assign the filename
            string fileName = "c:\\UserNames.txt";

            // Create reader & open file
            TextReader textReader = new StreamReader(fileName);

            // Read text to end of file
            Console.WriteLine("Reading {0} - {1}", 
                textReader.GetType().Name, textReader.ReadToEnd());

            // close the stream
            textReader.Close();
        }
    }
}
Running the Code
Press F5 or click the Start Debugging (green arrow) button to build and execute your code. After your code compiles a black box (cmd prompt) appears and executes your code. Then exits before you can see the console. In order to fix this lets add a pause.

Last Minute Changes
Below "textReader.Close();" we need to pause the problem so that the output can be observed. The easiest way to do this is to accept user input. Once the user presses enter (or any other key) the code will continue to run. Add:

Code:
// Accept User Input
Console.Read();
Your code should now look similar to this:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ccFileRead
{
    class Program
    {
        static void Main(string[] args)
        {
            // Assign the filename
            string fileName = "c:\\UserNames.txt";

            // Create reader & open file
            TextReader textReader = new StreamReader(fileName);

            // Read text to end of file
            Console.WriteLine("Reading {0} - {1}", 
                textReader.GetType().Name, textReader.ReadToEnd());

            // close the stream
            textReader.Close();

            // Accept User Input
            Console.Read();
        }
    }
}
Build and Execute your program (F5 or Green Arrow).

Final Output
Your program now reads the text file you create, lists the TextRead type and displays all of the user names pausing at the end to allow user input.



If you have any questions or comments please post them here.
__________________
CodeCall Blog | CodeCall Wiki | Shareware Site | Linux Forum | Write a Blog
The CodeCall Wiki is now fully integrated with vBulletin users! Check it out and add some new pages!

Last edited by Jordan; 03-15-2008 at 10:11 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #2 (permalink)  
Old 02-25-2008, 08:42 PM
John's Avatar   
John John is offline
Co-Administrator
 
Join Date: Jul 2006
Age: 20
Posts: 3,433
Last Blog:
Google Web Toolkit
Rep Power: 20
John has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond repute
Send a message via AIM to John Send a message via MSN to John
Default

sweet tutorial
__________________
CodeCall Blog | CodeCall Wiki | Shareware | Linux Forum | My Blog
Chat with other CodeCall members on IRC; connect to irc.codecall.net and join #codecall
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 06-18-2008, 03:02 PM
Johnnyboy's Avatar   
Johnnyboy Johnnyboy is offline
Learning Programmer
 
Join Date: Nov 2005
Location: NC
Posts: 55
Last Blog:
How to restrict a Text...
Rep Power: 12
Johnnyboy is on a distinguished road
Default Re: Visual Studio 2008: C# Reading Files

Awesome Jordan. I've only used vb6 and .net until now. Within minutes I was able to convert this to a windows forms application instead of console and am quickly on my way in C#.

THANKS!

If anyone else was wondering, here is what Jordan did using a windows forms app and bringing up the results of a file in a messagebox.

Code:
        private void btnEngrave_Click(object sender, EventArgs e)
        {
            //assign the filename
            string fileName = "c:\\engraving.txt"; 
            
            //create reader and open the file
            TextReader textReader = new StreamReader(fileName);

            // Read text to end of file
            MessageBox.Show(textReader.ReadToEnd());

            textReader.Close();
        }
__________________
When things work the way they should it's a wonderful thing! It's the should part that gets me. visit me @ www.unseenbattle.net and drop me a line.

Last edited by Jordan; 06-18-2008 at 03:40 PM. Reason: Added code tags
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 06-18-2008, 04:02 PM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Re: Visual Studio 2008: C# Reading Files

Is this in response to my writing files tutorials?

I must say, I would never use the StreamReader object without exception handling - while the StreamWriter simply creates a new file or overwrites as necessary, the StreamReader simply throws exceptions.

Also, the same function can be achieved simply by using IO.File.ReadAllText(), a static method that alleviates the need for any extra objects.
__________________


Mr. Xav | Website | Forums | Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 06-18-2008, 04:55 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 9,224
Last Blog:
Ext JS or Ext GWT
Rep Power: 20
Jordan is just really niceJordan is just really niceJordan is just really niceJordan is just really nice
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Re: Visual Studio 2008: C# Reading Files

I believe this one was posted before yours although I can't remember. You should use try/catch on anything that throws exceptions although this isn't an exception catching tutorial so there was no need to include them (and then have to explain them) here. Sounds like an excellent tutorial idea though.
__________________
CodeCall Blog | CodeCall Wiki | Shareware Site | Linux Forum | Write a Blog
The CodeCall Wiki is now fully integrated with vBulletin users! Check it out and add some new pages!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #6 (permalink)  
Old 06-18-2008, 10:10 PM
Johnnyboy's Avatar   
Johnnyboy Johnnyboy is offline
Learning Programmer
 
Join Date: Nov 2005
Location: NC
Posts: 55
Last Blog:
How to restrict a Text...
Rep Power: 12
Johnnyboy is on a distinguished road
Default Re: Visual Studio 2008: C# Reading Files

thanks guys... good stuff. and very helpful at that.
__________________
When things work the way they should it's a wonderful thing! It's the should part that gets me. visit me @ www.unseenbattle.net and drop me a line.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 06-19-2008, 11:53 AM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Re: Visual Studio 2008: C# Reading Files

Quote:
Originally Posted by Jordan View Post
Sounds like an excellent tutorial idea though.
Is that a hint?
__________________


Mr. Xav | Website | Forums | Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 06-19-2008, 03:37 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 9,224
Last Blog:
Ext JS or Ext GWT
Rep Power: 20
Jordan is just really niceJordan is just really niceJordan is just really niceJordan is just really nice
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Re: Visual Studio 2008: C# Reading Files

Maybe....
__________________
CodeCall Blog | CodeCall Wiki | Shareware Site | Linux Forum | Write a Blog
The CodeCall Wiki is now fully integrated with vBulletin users! Check it out and add some new pages!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 06-20-2008, 11:54 AM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Re: Visual Studio 2008: C# Reading Files

We'll see. Perhaps for the CC T-shirt...
__________________


Mr. Xav | Website | Forums | Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Visual Studio 2008: C# Hello World Tutorial Jordan CSharp Tutorials 14 11-20-2008 02:53 PM
Visual Studio 2008 Express Beta 2 Download Jordan Programming News 2 08-03-2007 02:05 PM
Visual Studio 2005 and Windows Vista Jordan General Programming 3 01-22-2007 04:21 PM
Visual Studio 2005 Pro Won't Install CheeseBurgerMan Software Development Tools 10 09-22-2006 06:44 PM


All times are GMT -5. The time now is 11:48 AM.