by Dinesh Thakur Category: C# Libraries

Files are the great way to store data between instances of your application, or file can be used to transfer data between applications. All input and output in the .NET framework involve the abstract base class Stream. The Stream class supports reading and writing bytes. Stream integrates asynchronous support. Its default implementations define synchronous reads and writes in terms of their corresponding asynchronous methods, and vice versa.

All classes that represent streams inherit from the' Stream class. The Stream class and its derived classes provide a generic view of data sources and repositories, isolating the programmer from the specific details of the operating system and underlying devices.

Streams involve these fundamental operations:

• Streams can be read from.

Reading is the transfer of data from a stream into a data structure, such as an array of bytes.

• Streams can be written to.

Writing is the transfer of data from a data source into a stream.

• Streams can support seeking.

Seeking is the querying and modifying of the current position within a stream.

Depending on the underlying data source or repository, streams might support only some of these capabilities. For example, NetworkStreams do not support seeking there are type of streams:

 

• Output streams: These are used to write data on the external sources such as phesical disk file, a network location, a printer or another program.

• Input streams: These are used to read data into memory or variables that your program can access. Mostly used input stream is keyboard. An input stream can come from almost any source.

Classes for Input and Output

The System.IO namespace contains almost all of the classes for reading and writing data to and from files, you must reference this in your application to gain access to theses classes. Stream supports· synchronous and asynchronous reads and writes. The .NET Framework provides a number of classes derived from Stream, including FileStream, MemoryStream, and NetworkStream. In addition, there is a BufferedStream class, which provides buffered I/O and which can be used in conjunction with any of the other stream classes. The principal classes involved with I/O are summarized in Table.

       The principal classes

Reading Text File

 

The following code examples show how to read text from a text file. The second example notifies you when the end of the file is detected.

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 disp1ay 1ines from the fi1e 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.

Conso1e.writeline( "The fi1e cou1d not be read:");

Console.writeline(e.Message);

}

}

}

 

using System;

using system.IO;

public class TextFromFile

{

private const string FILE_NAME= "MyFile.txt";

public static void Main(String[] args)

{

if (!File.Exists(FILE_NAME)).

{

console.writeLine(“{0} does not exist.", FILE_NAME);

return;

}

using (streamReader sr = File.openText(FILE_NAME))

{

String input;

while ((input=sr.ReadLine())!=null)

{

console.writeLine(input);

}

Console.writeline ("The end of the stream has been reached.");

sr.close();

}

}

 

Writing Text File

 

The first example shows how to add text to an e2cisting file. The second example shows how to create a new text file and write a string to it. Similar functionality can be provided by the WriteAlIText methods.

 

using system;

using system.Io;

class Test

{

public static void Main()

{

// Create an instance of streamwriter to write text to a

file.

// The using statement also closes the Streamwriter.

using (Streamwriter sw = new streamwriter(UTestFile.txt"))

{

// Add some text to the file.

sw.write(“This is the U);

sw.Writeline(‘header for the file.");

sw.writeLine("-------");

II Arbitrary objects can also be written to the file.

sw.write("The date is: ”);

sw.writeLine(DateTime.Now);

}

}

}

 

using system;

using system.Io;

public class TextToFile

{

private const string FILE_NAME = "MyFi1e.txt" ;

public static void Main(String[] args)

{

if (File.ExistS(FILE_NAME))·

{

Console.writeLine("{O} already exists.", FILE_NAME);

return;

}

using (streamwriter sw = File.createText(FILE_NAME))

{

sw.WriteLine ("This is my file.");

sw.WriteLine ("I can write ints {OJ or floats {1}, and so

on. " ,1, 4.2);

sw.close();

}

}

}

Reading and Writing to a Newly Created Data/Binary File

 

The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than character strings. The following code example demonstrates writing data to and reading data from a new, empty file stream (Test. data). After creating the data file in the current directory, the associated BinaryWriter and BinaryReader are created, and the Binary Writer is used to write the integers 0 through 10 to Test.data, which leaves the file pointer at the end of the file. After setting the file pointer back to the origin, the BinaryReader reads out the specified content.

 

using system;

using System.IO;

class MyStream

{

private const string FILE_NAME = "Test.data";

public static void Main(String[] args)

{

// Create the new, empty data f'l1e.

if (Fi1e.ExistS(FILE_NAME))

{

console.writeLine("{O} already exists!", FILE_NAME);

return;

}

Fi1eStream fs = new Filestream (FILE_NAME, FileMode.createNew);

// Create the writer for data.

Binarywriter w = new Binarywriter(fs);

// write data to Test.data.

for (int i = 0; i < 11; i++)

{

w.write( (int) i);

}

w.c1ose();

fs.c1ose();

// Create the reader for data.

fs = new FileStream(FILE_NAME, FileMode.open, Fi1eAccess.Read);

BinaryReader r = new BinaryReader(fs);

// Read data from Test.data.

for (int i = 0; i< 11; i++)

{

console.writeLine(r. ReadInt32 ());

}

r.C1ose();

fs.C1ose() ;

}

}

If Test.data already exists in the current directory, an IOException is thrown. Use FileMode.Create to always create a new file without throwing an IOException.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.