473,562 Members | 2,600 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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("T estFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLi ne(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLi ne("The file could not be read:");
Console.WriteLi ne(e.Message);
}
}
}

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

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

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

while (fs.Read(b,0,b. Length) > 0)
{
Console.WriteLi ne(temp.GetStri ng(b));
}
}
}
}
Nov 18 '05 #1
4 2722
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.

Bill456Smith567 89Mark456Wilson 6789Brian56Wint ers789

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******** ******@TK2MSFTN GP10.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("T estFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLi ne(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLi ne("The file could not be read:");
Console.WriteLi ne(e.Message);
}
}
}

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

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

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

while (fs.Read(b,0,b. Length) > 0)
{
Console.WriteLi ne(temp.GetStri ng(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******** ********@TK2MSF TNGP10.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.

Bill456Smith567 89Mark456Wilson 6789Brian56Wint ers789

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******** ******@TK2MSFTN GP10.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("T estFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLi ne(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLi ne("The file could not be read:");
Console.WriteLi ne(e.Message);
}
}
}

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

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

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

while (fs.Read(b,0,b. Length) > 0)
{
Console.WriteLi ne(temp.GetStri ng(b));
}
}
}
}


Nov 18 '05 #3
Hi,

Then all you have to do is:

sr.BaseStream.S eek(0, SeekOrigin.Begi n);
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******** ******@tk2msftn gp13.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******** ********@TK2MSF TNGP10.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.

Bill456Smith567 89Mark456Wilson 6789Brian56Wint ers789

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******** ******@TK2MSFTN GP10.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("T estFile.txt"))
{
String line;
// Read and display lines from the file until the end of // the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLi ne(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLi ne("The file could not be read:");
Console.WriteLi ne(e.Message);
}
}
}

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

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

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

while (fs.Read(b,0,b. Length) > 0)
{
Console.WriteLi ne(temp.GetStri ng(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******** ********@TK2MSF TNGP11.phx.gbl. ..
Hi,

Then all you have to do is:

sr.BaseStream.S eek(0, SeekOrigin.Begi n);
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
2088
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 I'm looking for a data file method that allows me to query and update the file from a VB app. I use MS Access/ASP on a daily basis and was hoping to...
7
6570
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 machine specific settings for a .NET program? And what classes, or code do we have to do this in C#? I don't think that using the myapp.config is the...
11
2407
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 out to an XML file? Use the CAB (Configuration Application Block)? Save the preferences in a class object and serialize them out the the XML file?...
4
11141
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 download from the MS site the DSOFile package containing the said DLL. However on looking in the newsgroups the best option to me seems to be using...
6
3124
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 and IIS) Authentication (not sure yet): existing user database, LDAP or permissions on directories (not sure if that last one is possible) ...
7
2218
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 so I can go and learn it myself through doing (best way for me). I am building a card game as a learning-project as it involves many (to most of...
8
3205
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. Therefore, when process finishes, "Exited" event is raised. This executable writes a long file for over 1-5 minutes, and I, from my application...
1
1710
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 and printing in the textpane attached to a scrollbar. I got heap dume(out of memory space) when a 21 mb file is being loaded. To avoid this I tried...
4
1917
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 / deleting material. I cannot use a .ini file because the .csv files could be called anything and come from any folder (i.e. it's a 'FileOpen'...
0
7579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7630
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7940
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6228
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5198
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3626
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3609
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1192
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
907
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.