• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C# » Libraries » FILE I/O in C#
Next →
← Prev

FILE I/O in C#

By Dinesh Thakur

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.

You’ll also like:

  1. Write a Program to Copy a File using File Handling Functions.
  2. Write a Program to Count Vowels in a File Using File Handling
  3. What is File Organizations? Types of File Organization.
  4. Copy Data From One File to Another File in Java Example
  5. File input Stream and File Output Stream
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C# Tutorials

C# Tutorials

  • C# - .NET Languages Types
  • C# - Dot Net
  • C# - Dot Net Framework
  • C# - Inheritance Types
  • C# - Features
  • C# - CTS
  • C# - CLS
  • C# - CLR
  • C# - Console
  • C# - MSIL
  • C# - Base Class Library
  • C# - Web Forms Creation
  • C# - C# Vs C++
  • C# - Statements Types
  • C# - JIT
  • C# - CLI
  • C# - Controls Types
  • C# - String Types
  • C# - Execution Model

Other Links

  • C# - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW