Friday, March 18, 2005

 

To Create a Text File

Use StreamWriter

Here’s an example

// Screen to file program
using System;
using System.IO;

class LearnStreamWriter
{
public static void Main()
{
StreamWriter fileOut = new StreamWriter("out.txt");
string str;

try {
Console.WriteLine("Enter text ('stop' to quit).");
Console.Write(": ");
while ( (str = Console.ReadLine() ) != "stop" )
{
Console.Write(": ");
fileOut.WriteLine(str);
}
}
catch( Exception e)
{
Console.WriteLine( e.Message);
}
finally
{
fileOut.Close();
}

// Read the file
StreamReader fileIn = new StreamReader("out.txt");

Console.WriteLine("\nYou wrote: ");
Console.WriteLine( fileIn.ReadToEnd() );
}
}

 

StreamReader

StreamReader is StreamWriter’s counterapart.

Here’s a short program to read a text file:

using System;
using System.IO;

class LearnStreamReadWrite
{
public static void Main()
{
string fileName = @"..\..\Class1.cs";

StreamReader fileRead = new StreamReader(fileName);

// Read the content of the file
string aLine = null;
while( (aLine = fileRead.ReadLine()) != null )
{
Console.WriteLine(aLine);
}

}

}

 

StreamWriter

StreamWriter is a character stream wrapper that inherits from TextWriter and is used to wrap a byte IO stream.

StreamWriter(Stream stream)

One way is to use a FileStream object as its constructor such as:


FileStream fout = new FileStream("test.txt", FileMode.Create);
StreamWriter fileOut = new StreamWriter(fout);
Another way is to use the static File members

StreamWriter fileOut = File.CreateText("test.txt"); 
or

StreamWriter fileOut = File.AppendText("test.txt"); 
More Convenient Way
A file can be opened directly using the StreamWriter by one of its constructors:

StreamWriter(string fileName)
StreamWriter(string fileName, bool appendFlag)

If appendFlag is true, the output is appended to the end of an existing file. If the file doesn’t exist, it is created.

StreamWriter.Write()
StreamWriter.WriteLine()
 

FileStream

FileStream enables manipulating of files via byte access.

FileStream is derived from Stream and contains all Stream’s functionality.

To create a byte straem linked to a file, create a FileStream object:

FileStream(string fileName, FileMode mode)

This constructor will depending on the mode specified, access the file with read / write capability

FileMode
FileMode.Append
Output is appended to the end of file

FileMode.Create
Creates a new output file. Any existing file with the same name will be deleted.

FileMode.CreateNew
Creates a new output file - the file must not already exist. (If the file exist, IOException will be thrown)

FileMode.Open
Opens an existing file

FileMode.OpenOrCreate
Opens a file if it exists, or creates the file if it does not already exist.

FileMode.Truncate
Opens a pre-existing file, but reduces its length to zero.

FileStream(string fileName, FileMode mode, FileAccess how)

The mode specifies how the file will be opened. FileAccess determines how the file can be accessed.

FileAccess.Read
Data can be read from the file

FileAccess.ReadWrite
Data can be written to and read from the file

FileAccess.Write
Data can be written to the file

void FileStream.Close()
When one’s done with the file, the Close() method should be called.

Read from a File

int FileStream.ReadByte()
Each time it is called, a single byte from the file is read and returns it as an integer value. When the end of file is encounted, it returns -1

int FileStream.Read(byte[] buf, int offset, int numBytes)
Read() attempts to read up to numBytes bytes into buf starting at buf[offset]. It retuns the number of bytes successfully read.

Write to a File

void FileStream.WriteByte(byte value)
Writes a byte specified by value to the file. If an error occurs during the write, an IOException will be thrown.

void FileStream.Write(byte[] buf, int offset, int numBytes)
An array of bytes can be written to a file by calling Write(). It writes numBytes bytes from the array buf, beginning at buf[offset] to the file.

void FileStream.Flush()
Output is sometimes not immediately written to the file. It is buffered. To cause data to be written to files whether the buffer is full, call the Flush() method.
Output is

Friday, March 11, 2005

 

Console Input

Console IO is accomplished through the standard streams Console.In, Console.Out and Console.Error

Console.In
Console.In is an instance of TextReader. Console defines two input methods: Read() and ReadLine(). Read() returns the next character read from the console. It waits until the user presses a key and then returns the result. The character is returned as an int, which must be cast to char. Read() returns -1 on error or end of stream (one-past the last character). By default, console input is line-buffered, this means you must press Enter before any character will be sent to your program.

Read() Method
The Read() method is line-buffered. When you press Enter, a carriage-return (ASCII: 13), line-feed (ASCII:10) sequence are entered into the input stream. These characters are left-spending in the input until you read them.

This is a sample program that demonstrates this effect:
using System;
using System.IO;

class ConsoleInput
{
public static void Main()
{
char ch;
int chInt;

Console.WriteLine("To terminate this program, press F6 or Contol-Z");
Console.Write("Press any key followed by ENTER: ");

while( (chInt = Console.Read()) != -1 )
{
ch = (char) chInt;
Console.Write("You wrote: " );
if(! char.IsControl(ch) )
Console.WriteLine("\"{0}\"", ch );
else
Console.WriteLine( chInt );
}

}
}

Although Console’s methods are easiest way to read from Console.In, you can call methods on the underlying TextReader.

Here’s a program that does that:

using System;

class ReadTextReader
{
public static void Main()
{
string str;

Console.WriteLine("Enter some characters: ");
str = Console.In.ReadLine();

Console.WriteLine("You entered: \"{0}\"", str );
}
}


- End -
 

TextReader & TextWriter

To create a character stream, wrap a byte stream inside one of C#’s character stream wrappers. Character stream have TextReader and TextWriter as the abstract base class.

TextReader
Some of the methods of interest are:

Close()

int Peek()

int Read()

string ReadLine()

string ReadToEnd()

TextWriter
This class defines the versions of Write() and WriteLine()

Sunday, March 06, 2005

 

Streams - 1 (Draft)

This is a simple program to explore the static Directory class

using System;
using System.IO;
using System.Diagnostics;
using System.Threading;

///
/// This program displays the folders of E:\DeleteMe
///

class DisplayDirectory
{
static string folder = @"E:\DeleteMe";
static string createFolder = @"E:\DeleteMe2";

public static void Main()
{
Console.WriteLine("folder = " + folder + "\n");

try {
// Does directory exists?
Console.WriteLine("Directory.Exists({0}) = {1}", folder, Directory.Exists(folder) );

// Create directory
Console.WriteLine("\nCreating folder " + createFolder);
if( ! Directory.Exists(createFolder) ) // If directory doesn't exists
Directory.CreateDirectory(createFolder);

Debug.Assert(Directory.Exists(createFolder), // Folder should exists
"Folder " + createFolder + " should exist");

// DIsplay the time the folder was created
DateTime folderTime = Directory.GetCreationTime(createFolder);
Console.WriteLine("Time {0} was created is {1}", createFolder, folderTime.ToString() );


// Display the current folder
Console.WriteLine("\nThe current directory is " + Directory.GetCurrentDirectory() );

// Display the directories in E: Console.WriteLine("\n" + @"E:\ contains ... ");
foreach(string directory in Directory.GetDirectories(@"E:\") )
{
Console.Write(directory + "\t");
}
Console.WriteLine("\n");

// Display directories in E:\ that starts with "C"
Console.WriteLine(@"E:\ subdirectories that starts with C... ");
foreach(string directory in Directory.GetDirectories(@"E:\", "C*.*") )
{
Console.Write(directory + "\t");
}
Console.WriteLine();

// Get the directory root
Console.WriteLine("\nDirectory.GetDirectoryRoot(createFolder) = " +
Directory.GetDirectoryRoot(createFolder) );

Console.WriteLine(@"Directory.GetDirectoryRoot(""."") = " +
Directory.GetDirectoryRoot(".") );

// Get the files in the current folder
Console.WriteLine("\nFiles in the current folder \".\" ({0}) are: ", Directory.GetCurrentDirectory() );
foreach(string files in Directory.GetFiles(".") )
{
Console.Write("{0}\t", files);
}
Console.WriteLine();

// Get ALL the files and subdirectories of E:\C#\Database
Console.WriteLine("\nAll Files and directories in " + @"E:\C#\Database" + " are:" );
foreach(string files in Directory.GetFileSystemEntries(@"E:\C#\Database") )
{
Console.Write("{0}\t", files);
}
Console.WriteLine();

// Sleep for awhile
//Thread.Sleep(TimeSpan.FromSeconds(3) );

// Get and set the ACCESS time of the folder E:\DeleteMe2
// Access teh folder (so that access time is NOW)
Directory.GetFileSystemEntries(createFolder);
// Get the time
Console.WriteLine("\nAccess time for {0} is {1}",
createFolder, Directory.GetLastAccessTime(createFolder) );

// Set the access time
Directory.SetLastAccessTime(createFolder, new DateTime(2012, 12, 12, 12, 12, 12) );
// Get the time
Console.WriteLine("\n\tAccess time for {0} AFTER SETTING is {1}",
createFolder, Directory.GetLastAccessTime(createFolder) );

// Get and set WRITE tiem of the folder E:\DeleteME
Console.WriteLine("\nWritten time for {0} REAL {1}",
createFolder, Directory.GetLastWriteTime(createFolder) );

// Set the write time
Directory.SetLastWriteTime(createFolder, new DateTime(2012, 12, 12, 12, 12, 12) );

Console.WriteLine("\n\tWritten time for {0} AFTER SETTING {1}",
createFolder, Directory.GetLastWriteTime(createFolder) );

// Get the dirves in this computer
Console.WriteLine("\nDrives in this computer: ");
foreach(string drives in Directory.GetLogicalDrives() )
{
Console.Write("{0}\t", drives);
}
Console.WriteLine();

// Get the parent folder in DirectoryInfo
DirectoryInfo parent = Directory.GetParent(".");
Console.WriteLine("\nParent = " + parent);

// Directory.Move()
// Make some directories in E:\DeleteMe\Shaohen
Directory.CreateDirectory(@"E:\DeleteMe\Shaohen");

Debug.Assert(Directory.Exists(@"E:\DeleteMe\Shaohen"));

// Move the folder to E: // Note: The destination folder shouldn't exists, meaning
// If want to move E:\DeleteMe\Shaohen to E:\DeleteMe2 so that
// E:\DeleteMe2 has E:\DeleteMe2\Shaohen // Then the argument to Directory.Move() should be
// Directory.Move(@"E:\DeleteMe\Shaohen", @"E:\DeleteMe2\Shaohen");
// and not
// Directory.Move(@"E:\DeleteMe\Shaohen", @"E:\DeleteMe2");
Directory.Move(@"E:\DeleteMe\Shaohen", @"E:\DeleteMe2\Shaohen");

// Set current Directory to E:\DeleteMe
Directory.SetCurrentDirectory(folder);
// Get current Directory
Console.WriteLine("\nCurrent directory is " + Directory.GetCurrentDirectory() );


}

catch(Exception e)
{
Console.WriteLine("Error: " + e);
}
finally
{
// Delete the folder
Console.WriteLine("\nDeleting folder " + createFolder);
Directory.Delete(createFolder, true); // Delete the folder and
// all the subdirectories
Debug.Assert( !Directory.Exists(createFolder) );// Folder shouldn't exists
}

}


}

This page is powered by Blogger. Isn't yours?