Input And output in CSharp
This chapter is dedicated to input & output in C#. The input & output in C# is based on streams.Streams are objects to work with input/output. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. In C#, we have a Stream class, that is an abstract class for all streams. There are additional classes that derive from the Stream class and make the programming a lot easier.
MemoryStream
AMemoryStream
is a stream which works with data in a computer memory. using System;We write six numbers to a memory with a
using System.IO;
public class CSharpApp
{
static void Main() {
try
{
Stream ms = new MemoryStream(6);
ms.WriteByte(9);
ms.WriteByte(11);
ms.WriteByte(6);
ms.WriteByte(8);
ms.WriteByte(3);
ms.WriteByte(7);
ms.Position = 0;
int rs;
rs = ms.ReadByte();
do
{
Console.WriteLine(rs);
rs = ms.ReadByte();
} while (rs != -1);
ms.Close();
} catch (IOException e)
{
Console.WriteLine(e.Message);
}
}
}
MemoryStream
. Then we read those numbers and print them to the console. Stream ms = new MemoryStream(6);The line creates and initializes a
MemoryStream
object with a capacity of six bytes. ms.Position = 0;We set the position of the cursor in the stream to the beginning using the
Position
property. ms.WriteByte(9);The
ms.WriteByte(11);
ms.WriteByte(6);
...
WriteByte()
method writes a byte to the current stream at the current position. doHere we read all bytes from the stream and print them to the console.
{
Console.WriteLine(rs);
rs = ms.ReadByte();
} while (rs != -1);
ms.Close();Finally, we close the stream.
$ ./memory.exeOutput of the example.
9
11
6
8
3
7
StreamReader & StreamWriter
StreamReader reads characters from a byte stream. It defaults to UTF-8 encoding. StreamWriter writes characters to a stream in a particular encoding.using System;We have a file called languages. We read characters from that file and print them to the console.
using System.IO;
public class CSharpApp
{
static void Main() {
try
{
StreamReader stream = new StreamReader("languages");
Console.WriteLine(stream.ReadToEnd());
stream.Close();
} catch (IOException e)
{
Console.WriteLine("Cannot read file.");
Console.WriteLine(e.Message);
}
}
}
StreamReader stream = new StreamReader("languages");The
StreamReader
takes a file name as a parameter. Console.WriteLine(stream.ReadToEnd());The
ReadToEnd()
method reads all characters to the end of the stream. $ cat languagesWe have a languages file in the current directory. We print all lines of the file to the console.
Python
Visual Basic
PERL
Java
C
C#
$ ./readfile.exe
Python
Visual Basic
PERL
Java
C
C#
In the next example, we will be counting lines.
using System;Counting lines in a file.
using System.IO;
public class CSharpApp
{
static void Main() {
int count = 0;
try
{
StreamReader stream = new StreamReader("languages");
while(stream.ReadLine() != null)
{
count++;
}
Console.WriteLine("There are {0} lines", count);
stream.Close();
} catch (IOException e)
{
Console.WriteLine("Cannot read file.");
Console.WriteLine(e.Message);
}
}
}
while(stream.ReadLine() != null)In the while loop, we read a line from the stream with the
{
count++;
}
ReadLine()
method. It returns a line from the stream or null if the end of the input stream is reached. An example with
StreamWriter
follows. It is a class used for character output. using System;In the preceding example, we write characters to the memory.
using System.IO;
public class CSharpApp
{
static void Main() {
try
{
MemoryStream ms = new MemoryStream();
StreamWriter swriter = new StreamWriter(ms);
swriter.Write("ZetCode, tutorials for programmers.");
swriter.Flush();
ms.Position = 0;
StreamReader sreader = new StreamReader(ms);
Console.WriteLine(sreader.ReadToEnd());
swriter.Close();
sreader.Close();
} catch (IOException e)
{
Console.WriteLine(e.Message);
}
}
}
MemoryStream ms = new MemoryStream();A
MemoryStream
is created. It is a stream whose backing store is memory. StreamWriter swriter = new StreamWriter(ms);A
StreamWriter
class takes a memory stream as a parameter. This way, we are going to write characters to memory stream. swriter.Write("ZetCode, tutorials for programmers.");We write some text to the writer. The
swriter.Flush();
Flush()
clears all buffers for the current writer and causes any buffered data to be written to the underlying stream. ms.Position = 0;We set the current position within the stream to the beginning.
StreamReader sreader = new StreamReader(ms);Now we create an instance of the stream reader and read everything we have previously written.
Console.WriteLine(sreader.ReadToEnd());
FileStream
AFileStream
class uses a stream on a file on the filesystem. This class can be used to read from files, write to files, open them and close them. using System;We write some text in Russian azbuka to the file called author in the current working directory.
using System.IO;
using System.Text;
public class CSharpApp
{
static void Main() {
try
{
FileStream fstream = new FileStream("author", FileMode.Append);
byte[] bytes = new UTF8Encoding().GetBytes("Фёдор Михайлович Достоевский");
fstream.Write(bytes, 0, bytes.Length);
fstream.Close();
} catch (IOException e)
{
Console.WriteLine(e.Message);
}
}
}
using System.Text;We need the
System.Text
namespace for the UTF8Encoding
class. FileStream fstream = new FileStream("author", FileMode.Append);A
FileStream
object is created. The second parameter is a mode, in which the file is opened. The append mode opens the file if it exists and seeks to the end of the file, or creates a new file. byte[] bytes = new UTF8Encoding().GetBytes("Фёдор Михайлович Достоевский");We create an array of bytes from text in russian azbuka.
fstream.Write(bytes, 0, bytes.Length);We write the bytes to the file stream.
$ cat authorWe show the contents of the author file.
Фёдор Михайлович Достоевский
XmlTextReader
We can use streams to read xml data. TheXmlTextReader
is the class to read xml files in C#. The class is forward-only and read-only. We have the following xml test file.
<?xml version="1.0" encoding="utf-8" ?>
<languages>
<language>Python</language>
<language>Ruby</language>
<language>Javascript</language>
<language>C#</language>
</languages>
using System;This C# program reads data from the previously specified xml file and prints it to the terminal.
using System.IO;
using System.Xml;
public class CSharpApp
{
static void Main() {
string file = "languages.xml";
try
{
XmlTextReader xreader = new XmlTextReader(file);
xreader.MoveToContent();
while (xreader.Read())
{
switch (xreader.NodeType)
{
case XmlNodeType.Element:
Console.Write(xreader.Name + ": ");
break;
case XmlNodeType.Text:
Console.WriteLine(xreader.Value);
break;
}
}
xreader.Close();
} catch (IOException e)
{
Console.WriteLine("Cannot read file.");
Console.WriteLine(e.Message);
} catch (XmlException e)
{
Console.WriteLine("XML parse error");
Console.WriteLine(e.Message);
}
}
}
using System.Xml;We import the
System.Xml
namespace, which contains classes related to Xml reading and writing. XmlTextReader xreader = new XmlTextReader(file);An
XmlTextReader
object is created. It is a reader that provides fast, non-cached, forward-only access to XML data. It takes the file name as a parameter. xreader.MoveToContent();The
MoveToContent()
method moves to the actual content of the xml file. while (xreader.Read())This line reads the next node from the stream. The
Read()
method returns false, if there are no more nodes left. case XmlNodeType.Element:Here we print the element name and element text.
Console.Write(xreader.Name + ": ");
break;
case XmlNodeType.Text:
Console.WriteLine(xreader.Value);
break;
} catch (XmlException e)We check for xml parse error.
{
Console.WriteLine("XML parse error");
Console.WriteLine(e.Message);
}
$ ./readxml.exeOutput of example.
language: Python
language: Ruby
language: Javascript
language: C#
Files and directories
The .NET framework provides other classes that we can use to work with files and directories.A
File
class is a higher level class that has static methods for file creation, deletion, copying, moving and opening. These methods make the job easier. using System;In the example, we create a cars file and write some car names into it.
using System.IO;
public class CSharpApp
{
static void Main() {
try
{
StreamWriter sw = File.CreateText("cars");
sw.WriteLine("Hummer");
sw.WriteLine("Skoda");
sw.WriteLine("BMW");
sw.WriteLine("Volkswagen");
sw.WriteLine("Volvo");
sw.Close();
} catch (IOException e)
{
Console.WriteLine("IO error");
Console.WriteLine(e.Message);
}
}
}
StreamWriter sw = File.CreateText("cars");The
CreateText()
method creates or opens a file for writing UTF-8 encoded text. It returns a StreamWriter
object. sw.WriteLine("Hummer");We write two lines to the stream.
sw.WriteLine("Skoda");
...
$ cat carsWe have successfully written five car names to a cars file.
Hummer
Skoda
BMW
Volkswagen
Volvo
using System;In the second example, we show other five static methods of the File class.
using System.IO;
public class CSharpApp
{
static void Main() {
try
{
if (File.Exists("cars"))
{
Console.WriteLine(File.GetCreationTime("cars"));
Console.WriteLine(File.GetLastWriteTime("cars"));
Console.WriteLine(File.GetLastAccessTime("cars"));
}
File.Copy("cars", "newcars");
} catch (IOException e)
{
Console.WriteLine("IO error");
Console.WriteLine(e.Message);
}
}
}
if (File.Exists("cars"))The
Exists()
method determines whether the specified file exists. Console.WriteLine(File.GetCreationTime("cars"));We get creation time, last write time and last access time of the specified file.
Console.WriteLine(File.GetLastWriteTime("cars"));
Console.WriteLine(File.GetLastAccessTime("cars"));
File.Copy("cars", "newcars");The
Copy()
method copies the file. $ ./copyfile.exeOutput of the example on my system.
10/16/2010 11:48:54 PM
10/16/2010 11:48:54 PM
10/16/2010 11:48:57 PM
The
System.IO.Directory
is a class, which has static methods for creating, moving, and enumerating through directories and subdirectories. using System;We will use two methods from the above mentioned object. We create two directories and rename one of the created ones.
using System.IO;
public class CSharpApp
{
static void Main() {
try
{
Directory.CreateDirectory("temp");
Directory.CreateDirectory("newdir");
Directory.Move("temp", "temporary");
} catch (IOException e)
{
Console.WriteLine("Cannot create directories");
Console.WriteLine(e.Message);
}
}
}
Directory.CreateDirectory("temp");The
CreateDirectory()
method creates a new directory. Directory.Move("temp", "temporary");The
Move()
method gives a specified directory a new name. The
DirectoryInfo
and Directory
have methods for creating, moving, and enumerating through directories and subdirectories. using System;We use the
using System.IO;
public class CSharpApp
{
static void Main() {
try
{
DirectoryInfo dir = new DirectoryInfo("../io");
string[] files = Directory.GetFiles("../io");
DirectoryInfo[] dirs = dir.GetDirectories();
foreach(DirectoryInfo subDir in dirs)
{
Console.WriteLine(subDir.Name);
}
foreach(string fileName in files)
{
Console.WriteLine(fileName);
}
} catch (IOException e)
{
Console.WriteLine(e.Message);
}
}
}
DirectoryInfo
class to traverse a specific directory and print its contents. DirectoryInfo dir = new DirectoryInfo("../io");We will show the contents of this directory (io).
string[] files = Directory.GetFiles("../io");We get all files of the io directory using the static
GetFiles()
method. DirectoryInfo[] dirs = dir.GetDirectories();We get all directories.
foreach(DirectoryInfo subDir in dirs)Here we loop through directories and print their names to the console.
{
Console.WriteLine(subDir.Name);
}
foreach(string fileName in files)Here we loop through the array of files and print their names to the console.
{
Console.WriteLine(fileName);
}
$ ./showcontents.exeOutput of the example.
newdir
temporary
../io/author
../io/cars
../io/cars.cs
../io/cars.cs~
../io/cars.exe
...
In this chapter, we have covered Input/Output operations in C#.
Do you like this Tutorial? Please link back to this article by copying one of the codes below.
URL: HTML link code: BB (forum) link code:
No comments: