Posted by John Lockwood on October 7th, 2009
This short sample shows different ways to read and write binary files and text files. In particular, note the two different techniques for reading and writing text files.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
// This sample demonstrates simple techniques for reading and writing text and binary files
class SimpleFileIO
{
static void Main(string[] args)
{
try
{
SimpleFileIO sfio = new SimpleFileIO();
// Step into each of these functions to see how to read / write
// different types of files.
sfio.TextFilesOneWay();
sfio.TextFilesAnotherWay();
sfio.BinaryFiles();
}
catch (Exception e)
{
Console.WriteLine(e.Message + "\n" + e.StackTrace);
}
finally
{
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
void TextFilesOneWay()
{
// Use the constructor of the StreamWriter and StreamReader
// classes to use a read and write text files
string filename = "SimpleFileIO_hello.txt";
StreamWriter sw = new StreamWriter(filename);
sw.WriteLine("Hello world");
sw.Close();
// Same technique to read it back
StreamReader sr = new StreamReader(filename);
string contents = sr.ReadLine();
sr.Close();
// Prove it
Console.WriteLine("\nUsing StreamWriter / StreamReader");
Console.WriteLine("Read and wrote file: {0} with contents:\n{1}",
filename, contents);
// Clean up
File.Delete(filename);
}
void TextFilesAnotherWay()
{
string filename = "SimpleFileIO_hello.txt";
// Another way to read and write text files
// uses the File class's static methds to get a TextWriter / TextReader
// Writing -- use CreateText to get a TextWriter on a new text file
TextWriter tw = File.CreateText(filename);
tw.WriteLine("Hello world");
tw.Close();
// Use OpenText to get a TextReader
TextReader tr = File.OpenText(filename);
string contents = tr.ReadLine();
tr.Close();
// Prove it
Console.WriteLine("\nUsing TextWriter / TextReader");
Console.WriteLine("Read and wrote file: {0} with contents:\n{1}",
filename, contents);
// Clean up
File.Delete(filename);
}
void BinaryFiles()
{
// Write binary files using BinaryWriter / Binary Reader
string filename = "SimpleFileIO_binary.bin";
// Use BinaryWriter constructor on a file
BinaryWriter bw = new BinaryWriter(
File.Open(filename, FileMode.Create));
// Write some bytes (for example)
for (byte i = byte.MinValue; i < byte.MaxValue; i++)
{
bw.Write(i);
}
bw.Close();
// Read them back, with a simple test
BinaryReader br = new BinaryReader(
File.Open(filename, FileMode.Open));
bool readFailed = false;
for (byte i = byte.MinValue; i < byte.MaxValue ; i++)
{
if (br.ReadByte() != i)
readFailed = true;
}
br.Close();
// Prove it
Console.WriteLine("\nWrite and read of binay file {0}: {1}",
filename,
readFailed ? "failed" : "succeded");
// Clean up
File.Delete(filename);
}
}
Posted in Implementing serialization and input/output functionality in a .NET Framework application | Add a comment »
Posted by John Lockwood on October 3rd, 2009
In the spirit of our DriveInfo example, which was a little slip of a thing, here’s a DriveInfo example.
using System;
using System.Collections.Generic;
using System.IO;
class DirectoryInfoExample
{
static void Main(string[] args)
{
string dir = @"C:\";
Console.WriteLine("Listing directories underneath {0}", dir);
DirectoryInfo diList = new DirectoryInfo(dir);
foreach (DirectoryInfo di in diList.GetDirectories())
{
Console.WriteLine("{0}", di.FullName);
}
Console.WriteLine("Listing files in {0}", dir);
foreach (FileInfo fi in diList.GetFiles())
{
Console.WriteLine("File name: {0}\nCreated: {1},\nLength: {2} bytes",
fi.Name, fi.CreationTime, fi.Length);
}
Console.ReadKey();
}
}
Posted in Implementing serialization and input/output functionality in a .NET Framework application | Add a comment »
Posted by John Lockwood on September 28th, 2009
using System;
using System.IO;
class FileAndFileInfoExample
{
static void Main(string[] args)
{
// Show some mechanisms for creating, moving,
// copying and deleting files
try
{
// Get a couple of filenames
string file1 = @"C:\FileInfoExample_Sample.txt";
string file2 = @"C:\FileInfoExample_Sample2.txt";
// Create a text file.
TextWriter tw = File.CreateText(file1);
// Write a moving love poem into it.
tw.WriteLine("I had a girl.");
tw.WriteLine("Her name was Sue.");
tw.WriteLine("Loved her dear,");
tw.WriteLine("Loved her true.");
tw.WriteLine("Till one day");
tw.WriteLine("She broke my heart.");
tw.WriteLine("Took a shotgun -- ");
tw.WriteLine("Blew me apart.");
// Sealed with a kiss for Sue
tw.Close();
// Copy our beautiful creation
File.Copy(file1, file2);
// Delete the original
File.Delete(file1);
// Move the new file back using File
File.Move(file2, file1);
// Using FileInfo instead this time...
FileInfo fi = new FileInfo(file1);
// Copy it again.
fi.CopyTo(file2);
// Delete the original again
fi.Delete();
// Get file2
fi = new FileInfo(file2);
// Move it back to one.
fi.MoveTo(file1);
// Show our poem to the world
string [] lovePoem = File.ReadAllLines(file1);
foreach (string profoundLine in lovePoem)
{
Console.WriteLine(profoundLine);
}
// Make sure no jealous poets steal our work
fi = new FileInfo(file1);
fi.Delete();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
Posted in Implementing serialization and input/output functionality in a .NET Framework application | 2 Comments »
Posted by John Lockwood on September 26th, 2009
We have a new featured question over on the ASPWorkbench.
Here it is:
Which of the following are differences between XML Serialization and standard serialization? Check all that apply.
A) XML Serialization allows both public and private data members to be serialized, while standard serialization supports only public data.
B) Only standard serialization uses the [Serializable] attribute to determine if a class is serializable.
C) Using the BinaryFormatter class along with standard serialization allows for more runtime efficiency than XML Serialization.
D) Standard serialization does not support the SOAP protocol.
For the answer, head over to the Workbench while this is still the featured question. (I know, that’s a bit of a cheesy process, but I just haven’t yet had time to get the archives and the site registration going – coming soon though).
Posted in Implementing serialization and input/output functionality in a .NET Framework application | Add a comment »
Posted by John Lockwood on September 26th, 2009
Too easy.
using System;
using System.IO;
public class DriveInfoExample
{
public static void Main(string [] args)
{
DriveInfo [] dilist = DriveInfo.GetDrives();
foreach (DriveInfo di in dilist)
{
Console.WriteLine("Drive: {0}, type: {1}",
di.Name, di.DriveType);
}
Console.ReadKey();
}
}
Posted in Implementing serialization and input/output functionality in a .NET Framework application | Add a comment »
Posted by John Lockwood on September 24th, 2009
This is one of the study objectives for the Microsoft .NET Certification Exam, 70-536.
-
Format data based on culture information.
May include but is not limited to: Access culture and region information within a .NET Framework application; Format date and time values based on the culture; Format number values based on the culture; Perform culture-sensitive string comparison; Build a custom culture class based on existing culture and region classes.
-
Enhance the user interface of a .NET Framework application by using the System.Drawing namespace.
May include but is not limited to: Enhance the user interface of a .NET Framework application by using brushes, pens, colors, and fonts; Enhance the user interface of a .NET Framework application by using graphics, images, bitmaps, and icons; Enhance the user interface of a .NET Framework application by using shapes and sizes.
-
Enhance the text handling capabilities of a .NET Framework application, and search, modify, and control text within a .NET Framework application by using regular expressions.
May include but is not limited to: StringBuilder class; Regex class; Match class and MatchCollection class; Group class and GroupCollection class; Encode text by using Encoding classes.; Decode text by using Decoding classes.; Capture class and CaptureCollection class
Posted in Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application | 1 Comment »