+ All Categories
Home > Documents > Files and Streams

Files and Streams

Date post: 03-Nov-2015
Category:
Upload: shivuhc
View: 215 times
Download: 0 times
Share this document with a friend
Description:
C
15
Files and Streams Objectives This chapter provides complete knowledge on How to work with System.IO namespace How to work with Files, directories and Drives How to work with Streams Page 1 FILES AND
Transcript

Files and Streams

2

FILES AND STREAMS

ObjectivesThis chapter provides complete knowledge on How to work with System.IO namespace How to work with Files, directories and Drives How to work with Streams

IntroductionSystem.IO NamespaceIn the framework of .NET, the System.IO namespace is the region of the base class libraries devoted to file-based (and memory-based) input and output (I/O) services. Like any namespace, System.IO defines a set of classes, interfaces, enumerations, structures, and delegates. Many of the types within the System.IO namespace focus on the programmatic manipulation of physical directories and files. However, additional types provide support to read data from and write data to string buffers as well as raw memory locations. The below table elaborates the main classes under this namespace.

ClassPurpose/Use

Binary Reader and WriterRead and write primitive data types

Directory, File, DirectoryInfo, and FileInfoCreate, delete, and move files and directories. Get specific information about the files by making use of the properties defined in these classes.

FileStreamAccess the files in a random fashion

MemoryStreamAccess data stored in memory

StreamWriter and StreamReaderRead and write textual information

StringReader and StringWriterRead and write textual Information from a string buffer

In addition to these concrete class types, System.IO defines a number of enumerations, as well as a set of abstract classes (Stream, TextReader, TextWriter, and so forth). The Directory(Info) and File(Info) Types System.IO provides four types that allow you to manipulate individual files, as well as interact with a machines directory structure. The first two types, Directory and File, expose creation, deletion, copying, and moving operations using various static members. The closely related FileInfo and DirectoryInfo types expose similar functionality as instance-level methods (and therefore must be allocated with the new keyword).

FileInfo and DirectoryInfo are better choices for obtaining full details of a file or directory as their members tend to return strongly typed objects. In contrast, the Directory and File class members tend to return simple string values rather than strongly typed objects.

The Abstract FileSystemInfo Base ClassThe DirectoryInfo and FileInfo types receive many behaviors from the abstract FileSystemInfo base class. For the most part, the members of the FileSystemInfo class are used to discover general characteristics (such as time of creation, various attributes, and so forth) about a given file or directory.

Below table elaborates its properties and methods.PropertiesPurpose/Use

AttributesReturns attributes associated with a file. Takes FileAttributes enumeration values

CreationTimeReturns the time of creation of the file

ExistsChecks whether a supplied file is a directory or not

ExtensionReturns the file extension

LastAccessTimeReturns last accessed time of the file

FullNameReturns the full path of the file

LastWriteTimeReturns the time of last written activity to the file

NameReturns the name of a given file

Delete()Deletes a file. Be careful when using this method.

DirectoryInfoThe first creatable I/O-centric type you will examine is the DirectoryInfo class. This class contains a set of members used for creating, moving, deleting, and enumerating over directories and subdirectories. In addition to the functionality provided by its base class (FileSystemInfo), DirectoryInfo offers the key members in below table.

MemberUse

Create(), CreateSubdirectory()Create a directory (or set of subdirectories), given a path name

Delete()Deletes a directory and all its contents

GetDirectories()Returns an array of strings that represent all subdirectories in the current directory

GetFiles()Retrieves an array of FileInfo types that represent a set of files in the given directory

MoveTo()Moves a directory and its contents to a new path

ParentRetrieves the parent directory of the specified path

RootGets the root portion of a path

You begin working with the DirectoryInfo type by specifying a particular directory path as a constructor parameter. If you want to obtain access to the current working directory (i.e., the directory of the executing application), use the "." notation. Here are some

examples:// Bind to the current working directory.DirectoryInfo dir1 = new DirectoryInfo(".");

// Bind to C:\Windows, using a verbatim string.

DirectoryInfo dir2 = new DirectoryInfo(@"C:\Windows");

In the second example, you are making the assumption that the path passed into the constructor (C:\Windows) already exists on the physical machine. However, if you attempt to interact with a nonexistent directory, a System.IO.DirectoryNotFoundException is thrown. Thus, if you specify adirectory that is not yet created, you will need to call the Create() method before proceeding:// Bind to a nonexistent directory, then create it.DirectoryInfo dir3 = new DirectoryInfo(@"C:\MyCode\Testing");dir3.Create();

Once you have created a DirectoryInfo object, you can investigate the underlying directory contents using any of the properties inherited from FileSystemInfo.

class Program{static void Main(string[] args){Console.WriteLine("***** Fun with Directory(Info) *****\n");ShowWindowsDirectoryInfo();Console.ReadLine();}static void ShowWindowsDirectoryInfo(){// Dump directory information.DirectoryInfo dir = new DirectoryInfo(@"C:\Windows");Console.WriteLine("***** Directory Info *****");Console.WriteLine("FullName: {0}", dir.FullName);Console.WriteLine("Name: {0}", dir.Name);Console.WriteLine("Parent: {0}", dir.Parent);Console.WriteLine("Creation: {0}", dir.CreationTime);Console.WriteLine("Attributes: {0}", dir.Attributes);Console.WriteLine("Root: {0}", dir.Root);Console.WriteLine("**************************\n");}}

Files with the DirectoryInfo TypeDirectoryInfo dir = new DirectoryInfo(@"C:\Windows\Web\Wallpaper");// files with a *.txt extension.FileInfo[] TextFiles = dir.GetFiles("*.txt");foreach (FileInfo f in TextFiles){Console.WriteLine("File name: {0}", f.Name);Console.WriteLine("File size: {0}", f.Length);Console.WriteLine("Creation: {0}", f.CreationTime);Console.WriteLine("Attributes: {0}", f.Attributes);}

Creating Subdirectories with the DirectoryInfo TypeYou can programmatically extend a directory structure using the DirectoryInfo.CreateSubdirectory() method. This method can create a single subdirectory, as well as multiple nested subdirectories, in a single function call.

DirectoryInfo sourceDir = new DirectoryInfo("c:\\IIBC");sourceDir.Create(); orDirectoryInfo dir = new DirectoryInfo(".");dir.CreateSubdirectory("MyFolder");DirectoryInfo sourceDir = new DirectoryInfo("c:\\IIBC");sourceDir.Create(); orDirectoryInfo dir = new DirectoryInfo(".");dir.CreateSubdirectory("MyFolder");

Directory TypeGet Files from root Directoryclass Program { static void Main(string[] args) { Console.WriteLine("Using: " + Directory.GetCurrentDirectory()); Console.WriteLine(Directory.Exists("c:\\")); string[] aFiles = Directory.GetFiles("c:\\");

foreach (string s in aFiles) Console.WriteLine(s); } }// List all drives on current computer.string[] drives = Directory.GetLogicalDrives();Console.WriteLine("Here are your drives:");foreach (string s in drives)Console.WriteLine("--> {0} ", s);// Delete what was created.Console.WriteLine("Press Enter to delete directories");Console.ReadLine();Directory.Delete(string.Format(@"{0}\MyFolder",Environment.CurrentDirectory));

FileInfoFileInfo class allows you to obtain details regarding existing files on your hard drive (time created, size, file attributes, and so forth) and aids in the creation, copying, moving, and destruction of files.

FileInfo.Create() MethodFileInfo f = new FileInfo(@"C:\IIBC.txt");FileStream fs = f.Create();

Be aware that the FileStream object returned by FileInfo.Create() grants full read/writeaccess to all users.FileInfo.Open() Method

You can use the FileInfo.Open() method to open existing files as well as create new files with far more precision than FileInfo.Create(), given that Open() typically takes several parameters to qualify the overall structure of the file you are manipulating.

FileInfo f2 = new FileInfo(@"C:\Test2.dat");FileStream fs2 = f2.Open(FileMode.OpenOrCreate,FileAccess.ReadWrite, FileShare.None)

FileMode Enumeration values.ValuesPurpose/Use

AppendOpens the file and adds data. This should be used with the FileAccess Write Enumeration value.

CreateCreates a new file. Overwrites any existing file.

CreateNewCreates a new file. If the file already exists, IOException is thrown.

OpenOpens an existing file

OpenOrCreateOpens a new file. If there is no file, it creates a new file.

TruncateTruncates an existing file

FileAccess Enumeration values ValuesPurpose/Use

ReadData can be read (retrieved) from the file

ReadWriteData can be added to and retrieved from the file

WriteData can be added to the file

FileInfo.OpenRead()FileInfo f3 = new FileInfo(@"C:\Test3.dat");using(FileStream readOnlyStream = f3.OpenRead())

FileInfo.OpenWrite()FileInfo f4 = new FileInfo(@"C:\Test4.dat");using(FileStream writeOnlyStream = f4.OpenWrite())

FileInfo.OpenText()FileInfo f5 = new FileInfo(@"C:\boot.ini");using(StreamReader sreader = f5.OpenText())

FileInfo.CreateText() and FileInfo.AppendText()FileInfo f6 = new FileInfo(@"C:\Test5.txt");using(StreamWriter swriter = f6.CreateText())

FileInfo f7 = new FileInfo(@"C:\FinalTest.txt");using(StreamWriter swriterAppend = f7.AppendText())

File TypeThe File type provides functionality almost identical to that of the FileInfo type, using a number of static members. Like FileInfo, File supplies AppendText(), Create(), CreateText(), Open(), OpenRead(), OpenWrite(), and OpenText()methods.

static void Main(string[] args){// Obtain FileStream object via File.Create().using(FileStream fs = File.Create(@"C:\Test.dat")){}// Obtain FileStream object via File.Open().using(FileStream fs2 = File.Open(@"C:\Test2.dat",FileMode.OpenOrCreate,FileAccess.ReadWrite, FileShare.None)){}// Get a FileStream object with read-only permissions.using(FileStream readOnlyStream = File.OpenRead(@"Test3.dat")){}// Get a FileStream object with write-only permissions.using(FileStream writeOnlyStream = File.OpenWrite(@"Test4.dat")){}// Get a StreamReader object.using(StreamReader sreader = File.OpenText(@"C:\boot.ini")){}// Get some StreamWriters.using(StreamWriter swriter = File.CreateText(@"C:\Test3.txt")){}using(StreamWriter swriterAppend = File.AppendText(@"C:\FinalTest.txt")){}}

Example:

class Program { static void Main(string[] args) { StreamWriter writer = new StreamWriter(@"c:\myfile.txt"); for (int i = 0; i < 3; i++) { writer.Write(i.ToString()); } foreach (string line in File.ReadAllLines(@"c:\myfile.txt")) { Console.WriteLine(line); } } }

classMainClass{publicstaticvoidMain(string[]args){FileInfofile=newFileInfo("c:\\test.txt");

Console.WriteLine("Checkingfile:"+file.Name);Console.WriteLine("Fileexists:"+file.Exists.ToString());

if(file.Exists){Console.Write("Filecreated:");Console.WriteLine(file.CreationTime.ToString());Console.Write("Filelastupdated:");Console.WriteLine(file.LastWriteTime.ToString());Console.Write("Filelastaccessed:");Console.WriteLine(file.LastAccessTime.ToString()); Console.Write("Filesize(bytes):");Console.WriteLine(file.Length.ToString());Console.Write("Fileattributelist:");Console.WriteLine(file.Attributes.ToString());

}}}

The Abstract Stream ClassIn the world of I/O manipulation, a stream represents a chunk of data flowing between a source and a destination. Streams provide a common way to interact with a sequence of bytes, regardless of what kind of device (file, network connection, printer, etc.) is storing or displaying the bytes in question. The abstract System.IO.Stream class defines a number of members that provide support for synchronous and asynchronous interactions with the storage medium.

Working with FileStreamsThe FileStream class provides an implementation for the abstract Stream members in a manner appropriate for file-based streaming. It is a fairly primitive stream; it can read or write only a single byte or an array of bytes.

FileStreamfin=newFileStream("test.dat",FileMode.Open);//Writethealphabet.for(inti=0;i


Recommended