Chapter 11 – Files and Serialization

SAMS CSHARP 4.0 (Page 194)

* Create, Read and Write Files

Two modes to access files: TEXT and BINARY.

In Text mode, raw contents are converted to System.String. most I/O in .Net are handled with the concept of streams, which are copnceptual buffers of data
that you can read/write in a linear fashion. Some streams allo you to jump to an arbitrary location in the streams, other don’t.

Open a text file to write:
StreamWriter writer = File.CreateText(destFileName);
writer.WriteLine(“text to write”);

Open a text file to read:
StreamReader reader = File.OpenText(destFileName);
String linetext = reader.ReadLine();

Need tro using System.IO;

Delete a File

Use File class’s static method:

Get a File Size

Use FileInfo class:
FileInfo info = new FileInfo(@”C:\myfile.txt”);
long size = info.Length;

Check file and directory Existence

Stirng target=@”D;\Files”;
if (File.Exists(target))
Console.WriteLine(“File exists”);
else if (Directory.Exists(target))
Console.WriteLine(“Directory Exists”);

Enumerate Directories and Files

You want to get a (possibly recursive) list of all directories and files

* DirectoryInfo can retrieve a list of subdirectories and files inside of it.

Create Unique or Temporary FileNames

// Get the faull path of a ramdom file name
string temfilename = Path.GetTempFileName();

// Get the random file name (only)
string filename = Path.GetRandomFileName();


Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: