473,406 Members | 2,467 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,406 software developers and data experts.

Basic File I/O in C#

Hey all, my name is Dan and I'm brand new to C#; all my previous
programming has been in VB6, so this is quite a change. I'd like to
read to and write from a simple text file that's in the app
directory. How do I do that, and what's the accepted way to store
the file in memory? I know in VB it was a string array, but...
anyhow, this is the code I'd use in VB just in case I need to be more
clear:

Dim StringArray() as String
Dim StringLine as String
Dim UB4Array as Integer

Open FileName for Input as #1
Do While Not EOF(1)
Line Input #1, StringLine
If (Not StringArray) = -1 then Redim StringArray(0)
UB4Array = UBound(StringArray) + 1
Redim Preserve StringArray(UB4Array)
StringArray(UBound(StringArray)) = StringLine
Loop
Close #1

That of course is just for input, and I need to know output too, but
that should suffice. Thanks in advance.

Dan

Nov 16 '05 #1
6 14841
Have a look at the StreamReader and StreamWriter classes.
Here is an example from MSDN:

using System;
using System.IO;

class Test
{

public static void Main()
{
// this is known as a verbatim string, the @ prevents escape
characters, without it you would have to use \\ instead of \
string path = @"c:\temp\MyTest.txt";

try
{
if (File.Exists(path))
{
File.Delete(path);
}

using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
}

using (StreamReader sr = new StreamReader(path))
{

while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
Chris

"dipique" <br******@juno-dot-com.no-spam.invalid> wrote in message
news:41**********@Usenet.com...
Hey all, my name is Dan and I'm brand new to C#; all my previous
programming has been in VB6, so this is quite a change. I'd like to
read to and write from a simple text file that's in the app
directory. How do I do that, and what's the accepted way to store
the file in memory? I know in VB it was a string array, but...
anyhow, this is the code I'd use in VB just in case I need to be more
clear:

Dim StringArray() as String
Dim StringLine as String
Dim UB4Array as Integer

Open FileName for Input as #1
Do While Not EOF(1)
Line Input #1, StringLine
If (Not StringArray) = -1 then Redim StringArray(0)
UB4Array = UBound(StringArray) + 1
Redim Preserve StringArray(UB4Array)
StringArray(UBound(StringArray)) = StringLine
Loop
Close #1

That of course is just for input, and I need to know output too, but
that should suffice. Thanks in advance.

Dan

Nov 16 '05 #2
Christopher Kimbell <c_*******@online.nospam> wrote:
using (StreamReader sr = new StreamReader(path))
{

while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}


I would personally use:

using (StreamReader sr = new StreamReader(path))
{
string line;

while ( (line=sr.ReadLine()) != null)
{
// Do something with line
}
}

Also, for the OP - when using StreamReader, the default encoding is
UTF-8, which may or may not be what you want. You can specify a
different encoding in the constructor though.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #3
Thanks, I've got it:)

Dan

Nov 16 '05 #4
Hello, dipique!
This is how I do that:
////////////////////////////////////
using System;

namespace FileRW_CS
{
public class ReadWrite
{
private string FileName;

public ReadWrite()
{
this.FileName="default.txt";
}

public ReadWrite(String fileName)
{
this.FileName=fileName;
}

public String readData ()
{
string s="";
System.IO.FileStream fs=System.IO.File.Open(
this.FileName,
System.IO.FileMode.OpenOrCreate,
System.IO.FileAccess.Read,
System.IO.FileShare.Read);
int x=-2;
while (true)
{
x=fs.ReadByte();
if (x==-1)
break;
char c=(char)x;
s+=c;
}
fs.Close();
return s;
}

public void writeData (String s)
{
if (System.IO.File.Exists(this.FileName))
System.IO.File.Delete(this.FileName);
System.IO.FileStream fs=System.IO.File.Open(
this.FileName,
System.IO.FileMode.OpenOrCreate,
System.IO.FileAccess.Write,
System.IO.FileShare.Read);

for (int i=0; i<s.Length; i++)
fs.WriteByte((byte)s[i]);

fs.Close();
}

public void deleteFile()
{
if (System.IO.File.Exists(this.FileName))
System.IO.File.Delete(this.FileName);
}
}
}
////////////////////////////////////
With best regards, Nurchi BECHED.
Nov 16 '05 #5
Why duplicate functionality that already exists?

On another point, If you still want to use this way, I would serioulsy
consider changing the 's' to a StringBuilder,
as the code is now, you will get massive string creation when you append the
character to the string.
Remember that strings are imutable, they cannot be changed once created, a
new string is allocated that is the result of the the previous added
together.

Chris
"Nurchi BECHED" <nu****@telus.net> wrote in message
news:A9fNc.120425$eO.1841@edtnps89...
Hello, dipique!
This is how I do that:
////////////////////////////////////
using System;

namespace FileRW_CS
{
public class ReadWrite
{
private string FileName;

public ReadWrite()
{
this.FileName="default.txt";
}

public ReadWrite(String fileName)
{
this.FileName=fileName;
}

public String readData ()
{
string s="";
System.IO.FileStream fs=System.IO.File.Open(
this.FileName,
System.IO.FileMode.OpenOrCreate,
System.IO.FileAccess.Read,
System.IO.FileShare.Read);
int x=-2;
while (true)
{
x=fs.ReadByte();
if (x==-1)
break;
char c=(char)x;
s+=c;
}
fs.Close();
return s;
}

public void writeData (String s)
{
if (System.IO.File.Exists(this.FileName))
System.IO.File.Delete(this.FileName);
System.IO.FileStream fs=System.IO.File.Open(
this.FileName,
System.IO.FileMode.OpenOrCreate,
System.IO.FileAccess.Write,
System.IO.FileShare.Read);

for (int i=0; i<s.Length; i++)
fs.WriteByte((byte)s[i]);

fs.Close();
}

public void deleteFile()
{
if (System.IO.File.Exists(this.FileName))
System.IO.File.Delete(this.FileName);
}
}
}
////////////////////////////////////
With best regards, Nurchi BECHED.

Nov 16 '05 #6
Nurchi BECHED <nu****@telus.net> wrote:
This is how I do that:


<snip>

As has been pointed out, the failure to use StringBuilder will
absolutely kill your performance here - try reading a 1M file with the
code below and you'll see it take *ages*.

Other problems:

o Your byte<->char conversion is assuming an encoding of ISO-8859-1
(pretty much) which often isn't what's wanted
o Calling ReadByte for each byte is a very slow way of reading data -
using Read with a buffer is much more efficient
o You're not closing the stream if an exception occurs - use a
using statement to do this easily
o Your original assignment to x is unnecessary as it's never read
o Your code would be somewhat more readable with a
using System.IO;
declaration at the start, and then using the shorter names
o It's generally a good idea to follow MS's naming conventions to
get consistency with the rest of the framework

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7

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

Similar topics

15
by: Simon | last post by:
I would like to create a very basic file upload add image form to add to my web site and to keep them in a "tmp" directory within my web hosting file manager once uploaded. I understand the basic...
2
by: Ralph | last post by:
I used to have Visual Basic .net std. 2003 installed on WinXP SP1A. But I found it too hard to upgrade WinXP to SP2. Now, I do have WinXP SP2 installed, but I am having problems installing...
1
by: Tom Rahav | last post by:
Hello all! I develop application in Visual Basic .NET and ORACLE database. My question is how do I "send" script file to the database using visual basic .net. Other words, is there any way to...
9
by: Malcolm | last post by:
After some days' hard work I am now the proud possessor of an ANSI C BASIC interpreter. The question is, how is it most useful? At the moment I have a function int basic(const char *script,...
8
by: Sam Collett | last post by:
Is there a basic guide on Xml document creation and editing (simpler than the MSDN docs). Say I want to create a file containing the following: <?xml version="1.0" encoding="utf-8"...
3
by: sefe dery | last post by:
hi ng, i try to create a asp.net 1.0 website on windows server 2003(Servername: ServerX) with iis 6.0. PROBLEM: The user should login with his windows credentials in basic.aspx and...
2
by: frossberg | last post by:
Hello! I tried to install the Visual Basic.NET Resource Kit (http://msdn.microsoft.com/vbasic/vbrkit/) but obviously something went very wrong and now it sems impossible both to repair and to...
21
by: Al Christoph | last post by:
I posted this last week end in the MSDN forums. No luck there. Let's see what the experts here have to say:-)))) I have a rather convoluted project. The distributable will come in eight...
7
by: garyusenet | last post by:
This is the first time i've worked with openfile dialog. I'm getting a couple of errors with my very basic code. Can someone point out the errors in what i've done please....
1
by: chrspta | last post by:
I am new to Visual basic. I need a program using VB6 that converts txt files to excel file.Description is in the below: The form should have the Drive list, Dir list, file list and cmdConvert...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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...
0
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.