Home SEO Tools HTML Escape Tool Character Counter Guest post

Input And output in CSharp

0 comments


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

A MemoryStream is a stream which works with data in a computer memory.
using System;
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);
}
}
}
We write six numbers to a memory with a 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);
ms.WriteByte(11);
ms.WriteByte(6);
...
The WriteByte() method writes a byte to the current stream at the current position.
do 
{
Console.WriteLine(rs);
rs = ms.ReadByte();
} while (rs != -1);
Here we read all bytes from the stream and print them to the console.
ms.Close();
Finally, we close the stream.
$ ./memory.exe 
9
11
6
8
3
7
Output of the example.

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;
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);
}
}
}
We have a file called languages. We read characters from that file and print them to the console.
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 languages 
Python
Visual Basic
PERL
Java
C
C#
$ ./readfile.exe
Python
Visual Basic
PERL
Java
C
C#
We have a languages file in the current directory. We print all lines of the file to the console.

In the next example, we will be counting lines.
using System;
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);
}
}
}
Counting lines in a file.
while(stream.ReadLine() != null)
{
count++;
}
In the while loop, we read a line from the stream with the 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;
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);
}
}
}
In the preceding example, we write characters to the memory.
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.");
swriter.Flush();
We write some text to the writer. The 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);
Console.WriteLine(sreader.ReadToEnd());
Now we create an instance of the stream reader and read everything we have previously written.

FileStream

A FileStream 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;
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);
}
}
}
We write some text in Russian azbuka to the file called author in the current working directory.
using System.Text;
We need the System.Text namespace for the UTF8Encodingclass.
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 author 
Фёдор Михайлович Достоевский
We show the contents of the author file.

XmlTextReader

We can use streams to read xml data. The XmlTextReader 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;
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);
}
}
}
This C# program reads data from the previously specified xml file and prints it to the terminal.
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:
Console.Write(xreader.Name + ": ");
break;
case XmlNodeType.Text:
Console.WriteLine(xreader.Value);
break;
Here we print the element name and element text.
} catch (XmlException e)
{
Console.WriteLine("XML parse error");
Console.WriteLine(e.Message);
}
We check for xml parse error.
$ ./readxml.exe 
language: Python
language: Ruby
language: Javascript
language: C#
Output of example.

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;
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);
}
}
}
In the example, we create a cars file and write some car names into it.
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");
sw.WriteLine("Skoda");
...
We write two lines to the stream.
$ cat cars
Hummer
Skoda
BMW
Volkswagen
Volvo
We have successfully written five car names to a cars file.

using System;
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);
}
}
}
In the second example, we show other five static methods of the File class.
if (File.Exists("cars"))
The Exists() method determines whether the specified file exists.
Console.WriteLine(File.GetCreationTime("cars"));
Console.WriteLine(File.GetLastWriteTime("cars"));
Console.WriteLine(File.GetLastAccessTime("cars"));
We get creation time, last write time and last access time of the specified file.
File.Copy("cars", "newcars");
The Copy() method copies the file.
$ ./copyfile.exe 
10/16/2010 11:48:54 PM
10/16/2010 11:48:54 PM
10/16/2010 11:48:57 PM
Output of the example on my system.

The System.IO.Directory is a class, which has static methods for creating, moving, and enumerating through directories and subdirectories.
using System;
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);
}
}
}
We will use two methods from the above mentioned object. We create two directories and rename one of the created ones.
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;
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);
}
}
}
We use the 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)
{
Console.WriteLine(subDir.Name);
}
Here we loop through directories and print their names to the console.
foreach(string fileName in files)
{
Console.WriteLine(fileName);
}
Here we loop through the array of files and print their names to the console.
$ ./showcontents.exe 
newdir
temporary
../io/author
../io/cars
../io/cars.cs
../io/cars.cs~
../io/cars.exe
...
Output of the example.
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:

FAQs | Privacy Policy | Contact | | Advertise | Donate