473,386 Members | 1,694 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Which way is best to read from a file?

Below is two snippets of code from MSDN showing how to read a file. Is one
way preferred over the other and why? Thanks.
using System;
using System.IO;

class Test
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

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

class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";

// Open the stream and read it
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);

while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}
Nov 18 '05 #1
4 2695
Hi,

Both ways are useful depending on what you need to accomplish. The top way
reads the file one line at a time meaning it reads till the line break. If
your file contains lists of names:

Bill
Smith
Mark
Wilson
Brian
Winters

Then reading line by line will work for you. However if your file is
created without using line breaks and instead has fixed length fields, then
the bottom way will let you grab these anywhere in the file instead of
having to iterate through all the lines.

Bill456Smith56789Mark456Wilson6789Brian56Winters78 9

The line above shows a fixed length field file (visualize a space where each
number is). Each first name takes up 7 characters, each last name takes up
10. So if you wanted to get the 3rd first name you would read 7 characters
starting at position 34 (remember streams start at 0). Good luck! Ken.

--
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.

"ESPN Lover" <es**@lover.com> wrote in message
news:Os**************@TK2MSFTNGP10.phx.gbl...
Below is two snippets of code from MSDN showing how to read a file. Is one
way preferred over the other and why? Thanks.
using System;
using System.IO;

class Test
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

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

class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";

// Open the stream and read it
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);

while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}

Nov 18 '05 #2
All I'm trying to do is copy the contents of a file (actually an HTML page
on the file system) into a string. Process the string and output a new
file. So the idea is to read, upfront, the entire file's contents and place
it into a string. This is manipulated and then I'll write out a new file.

"Ken Dopierala Jr." <kd*********@wi.rr.com> wrote in message
news:eV****************@TK2MSFTNGP10.phx.gbl...
Hi,

Both ways are useful depending on what you need to accomplish. The top way reads the file one line at a time meaning it reads till the line break. If your file contains lists of names:

Bill
Smith
Mark
Wilson
Brian
Winters

Then reading line by line will work for you. However if your file is
created without using line breaks and instead has fixed length fields, then the bottom way will let you grab these anywhere in the file instead of
having to iterate through all the lines.

Bill456Smith56789Mark456Wilson6789Brian56Winters78 9

The line above shows a fixed length field file (visualize a space where each number is). Each first name takes up 7 characters, each last name takes up 10. So if you wanted to get the 3rd first name you would read 7 characters starting at position 34 (remember streams start at 0). Good luck! Ken.

--
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.

"ESPN Lover" <es**@lover.com> wrote in message
news:Os**************@TK2MSFTNGP10.phx.gbl...
Below is two snippets of code from MSDN showing how to read a file. Is one way preferred over the other and why? Thanks.
using System;
using System.IO;

class Test
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

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

class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";

// Open the stream and read it
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);

while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}


Nov 18 '05 #3
Hi,

Then all you have to do is:

sr.BaseStream.Seek(0, SeekOrigin.Begin);
strEntireFile = sr.ReadToEnd();

Put that in the top version of the examples you showed in the place of the
while loop. Good luck! Ken.

--
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.

"ESPN Lover" <es**@lover.com> wrote in message
news:OJ**************@tk2msftngp13.phx.gbl...
All I'm trying to do is copy the contents of a file (actually an HTML page
on the file system) into a string. Process the string and output a new
file. So the idea is to read, upfront, the entire file's contents and place it into a string. This is manipulated and then I'll write out a new file.

"Ken Dopierala Jr." <kd*********@wi.rr.com> wrote in message
news:eV****************@TK2MSFTNGP10.phx.gbl...
Hi,

Both ways are useful depending on what you need to accomplish. The top

way
reads the file one line at a time meaning it reads till the line break.

If
your file contains lists of names:

Bill
Smith
Mark
Wilson
Brian
Winters

Then reading line by line will work for you. However if your file is
created without using line breaks and instead has fixed length fields,

then
the bottom way will let you grab these anywhere in the file instead of
having to iterate through all the lines.

Bill456Smith56789Mark456Wilson6789Brian56Winters78 9

The line above shows a fixed length field file (visualize a space where

each
number is). Each first name takes up 7 characters, each last name takes

up
10. So if you wanted to get the 3rd first name you would read 7

characters
starting at position 34 (remember streams start at 0). Good luck! Ken.

--
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.

"ESPN Lover" <es**@lover.com> wrote in message
news:Os**************@TK2MSFTNGP10.phx.gbl...
Below is two snippets of code from MSDN showing how to read a file. Is one way preferred over the other and why? Thanks.
using System;
using System.IO;

class Test
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of // the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

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

class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";

// Open the stream and read it
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);

while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}



Nov 18 '05 #4
Thanks, Ken!! That's what I was after :-)
"Ken Dopierala Jr." <kd*********@wi.rr.com> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
Hi,

Then all you have to do is:

sr.BaseStream.Seek(0, SeekOrigin.Begin);
strEntireFile = sr.ReadToEnd();

Put that in the top version of the examples you showed in the place of the
while loop. Good luck! Ken.

Nov 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Laphan | last post by:
Hi All I know this is my 2nd (and final) cross-post, but which NG should I use for the below. I want to create a game that queries and updates text and numeric stats on a regular basis, so...
7
by: | last post by:
In the beginning we had Ini files. Later we had registery files. Now have xml files and our read-only myapp.config file. My question now, is what is the best way to store and load user and...
11
by: Tom | last post by:
I am planning on adding a Preferences form to my application and using the Property Grid to display the preferences to the user. What do you think would be the best way to save these preferences...
4
by: Paul Bromley | last post by:
I have been pondering over this one all night!! I want to read the properties of a Word document WITHOUT opening it - notably the title document. Having read the newsgroups it seems that I neede to...
6
by: JM | last post by:
I have never used a (content management system) CMS before but I need one for my internship as a webdeveloper. Requirements: runs on Apache, linux or unix, MySQL and PHP (maybe Windows server...
7
by: Gladen Blackshield | last post by:
Hello All! Still very new to PHP and I was wondering about the easiest and simplest way to go about doing something for a project I am working on. I would simply like advice on what I'm asking...
8
by: Lonifasiko | last post by:
Hi, Using Process class I asynchronously launch an executable (black box executable) file from my Windows application. I mean asynchronously because I've got an EventHandler for "Exited" event....
1
by: amitpathak | last post by:
I am working on a project in which I am required to read a file and load the contents in some JComponent to show it to the users. I was reading the file with the help of stringbuffer/filebuffer...
4
by: TC | last post by:
Hey All, I have to read .csv files and display them in a DataGridView. Currently, I'm dumping the data into a DataTable but it's causing problems because the engine is automatically converting...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.