Basic File I/O in C#

  • Thread starter Thread starter dipique
  • Start date Start date
D

dipique

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
 
Christopher Kimbell said:
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.
 
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
 
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);

fs.Close();
}

public void deleteFile()
{
if (System.IO.File.Exists(this.FileName))
System.IO.File.Delete(this.FileName);
}
}
}
////////////////////////////////////
With best regards, Nurchi BECHED.
 
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 said:
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
 
Back
Top