Sie sind auf Seite 1von 6

Files and Streams

Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates. Data maintained in files often is called persistent data. Computers store files on secondary storage devices, such as magnetic disks, optical disks and magnetic tapes. File processing is one of a programming language's most important capabilities, because it enables a language to support commercial applications that typically process massive amounts of persistent data. Data Hierarchy All data items that computer processes are reduced to combinations of 0s and 1s. The smallest data item that computers support is called a bit and can assume either the value 0 or the value 1. Digits, letters and special symbols are referred to as characters. The set of all characters used to write programs and represent data items on a particular computer is called that computer's character set. Every character in a computer's character set is represented as a pattern of 0s and 1s. Bytes are composed of eight bits Characters in C# are Unicode characters, which are composed of 2 bytes. Just as characters are composed of bits, fields are composed of characters. A field is a group of characters that conveys meaning. Typically, a record is composed of several related fields. A file is a group of related records. At least one field in each record is chosen as a record key, which identifies a record as belonging to a particular person or entity and distinguishes that record from all others. The most common type of file organization is a sequential file, in which records typically are stored in order by record-key field. A group of related files is called a database. A collection of programs designed to create and manage databases is called a database management system (DBMS). Files and Streams C# views each file as a sequential stream of bytes. Each file ends either with an end-of-file marker or at a specific byte number that is recorded in a system-maintained administrative data structure. Files are opened by creating an object that has a stream associated with it. Streams provide communication channels between files and programs. To perform file processing in C#, the System.IO namespace must be referenced. This namespace includes definitions for stream classes such as StreamReader (for text input from a file), StreamWriter (for text output to a file) and FileStream (for both input from and output to a file). Properties Console.In and Console.Out are of type TexTReader and TextWriter, respectively.

Class Stream provides functionality for representing streams as bytes. This class is abstract, so objects of this class cannot be instantiated. Classes FileStream, MemoryStream and BufferedStream (all from namespace System.IO) inherit from class Stream. Class FileStream can be used to read data to and write data from sequential-access files. Class MemoryStream enables the transfer of data directly to and from memory. This is much faster than other types of data transfer (e.g., to and from disk). Class BufferedStream uses buffering to transfer data to or from a stream. Buffering is an I/O performance enhancement technique, in which each output operation is directed to a region in memory, called a buffer that is large enough to hold the data from many output operations. Then actual transfer to the output device is performed in one large physical output operation each time the buffer fills. The output operations directed to the output buffer in memory often are called logical output operations. Buffering can also be used to speed input operations.

Classes File and Directory


Information on computers is stored in files, which are organized in directories. Classes File and Directory enable programs to manipulate files and directories on disk. Class File provides static methods determining information about files and can be used to open files for reading or writing.
Figure 18.3 File class static methods (partial list)

Static Method AppendText Copy Create CreateText Delete Exists GetCreationTime

Description Returns a StreamWriter that appends text to an existing file or creates a file if one does not exist. Copies a file to a new file. Creates a file and returns its associated FileStream. Creates a text file and returns its associated StreamWriter. Deletes the specified file. Returns true if the specified file exists and false otherwise. Returns a DateTime object representing when the file was created.

GetLastAccessTime Returns a DateTime object representing when the file was last accessed. GetLastWriteTime Move Open OpenRead OpenText OpenWrite Returns a DateTime object representing when the file was last modified. Moves the specified file to a specified location. Returns a FileStream associated with the specified file and equipped with the specified read/write permissions. Returns a read-only FileStream associated with the specified file. Returns a StreamReader associated with the specified file. Returns a read/write FileStream associated with the specified file.

Class Directory provides static methods for manipulating directories.


Figure 18.4 Directory class static methods

Static Method CreateDirectory Delete Exists Getdirectories GetFiles GetCreationTime

Description Creates a directory and returns its associated DirectoryInfo object. The DirectoryInfo contains information about a directory. Deletes the specified directory. Returns true if the specified directory exists and false otherwise. Returns a string array containing the names of the subdirectories in the specified directory. Returns a string array containing the names of the files in the specified directory. Returns a DateTime object representing when the directory was created.

GetLastAccessTime Returns a DateTime object representing when the directory was last accessed. GetLastWriteTime Move Returns a DateTime object representing when items were last written to the directory. Moves the specified directory to a specified location.

A StreamReader can be used to read text from a file. The StreamReader constructor takes as an argument a string containing the name of the file to open. StreamReader method ReadToEnd reads the entire contents of a file.
// display file contents through StreamReader try { // obtain reader and file contents StreamReader stream = new StreamReader(fileName ); outputTextBox.Text += stream.ReadToEnd(); } // end try catch ( IOException ) // handle exception if StreamReader is unavailable { MessageBox.Show( "Error reading from file", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // end catch

FileStream: Use the FileStream to read from, write to, open, and close files, as well as to manipulate pipes, standard input, and standard output. FileStream buffers input and output for better performance. TextReader is the abstract base class of StreamReader, which read characters from streams. StreamReader is designed for character input. Use StreamReader for reading lines of information from a standard text file. BinaryReader: Reads primitive data types such as Integer, float , double etc. as binary values.

Reading and Writing to Files


1) Done through the File class and FileInfo object
Sr. No. Reading a File string str = File.ReadAll(FilePath); OR Writing a File File.WriteAll(FilePath, Content); OR File.WriteAll(FilePath, Content, Encoding); The WriteAll method went to the specified location, created a new text file, and provided the file the specified contents before saving and closing the file. Some of the other options for opening and working with files include using the WriteAllBytes and the WriteAllLines methods. The WriteAllBytes method allows you to write content to a file using a byte array, and the WriteAllLines method allows you to write a string array to a file. An example of this is illustrated in the following event handler: private void button1_Click(object sender, EventArgs e) { string[] movies = {"Grease", "Close Encounters", "The Day After Tomorrow"}; File.WriteAllLines("C:\Testing.txt", movies); } FileInfo myFile4 = new FileInfo(@"C:\C# Projects\Project4.doc"); FileStream fs4 = myFile4.OpenRead(); FileInfo myFile5 = new FileInfo(@"C:\C# Projects\Project5doc"); FileStream fs5 = myFile5.OpenWrite();

1.

string str = File.ReadAll(FilePath, Encoding); The return value of the ReadAll method is a string containing the entire contents of the file specified.

Some of the other options for opening and working with files include using the ReadAllBytes, ReadAllText and the ReadAllLines methods. ReadAllBytes method allows you to open up a binary file and read the contents into a byte array. string[] lines = File.ReadAllLines("file.txt"); string text1 = File.ReadAllText("file.txt"); byte[] _logoBytes = File.ReadAllBytes("Logo.png");

2.

3.

FileInfo myFile6 = new FileInfo(@"C:\C# Projects\Project6doc"); FileStream fs6 = myFile6.Open(FileMode.Append, FileAccess.Write, FileShare.None); FileInfo myFile7 = new FileInfo(@"C:\C# Projects\Project7.doc"); FileStream fs7 = myFile7.Create();

2) Done through the FileStream class


A stream is an object used to transfer data. The data can be transferred in one of two directions i.e. reading from the stream and writing to the stream. As far as reading and writing files is concerned, the classes that concern us most are: FileStream - This class is intended for reading and writing binary data in a binary file. However, you can also use it to read from or write to any file. StreamReader and StreamWriter - These classes are designed specifically for reading from and writing to text files.

Sr. No.

Reading a File
// creates file with read-write access and allows other streams read access FileStream fs = new FileStream(@"C:\C# Projects\Project1.doc",FileMode.Create); // as above, but we only get write access to the file FileStream fs2 = new FileStream(@"C:\C# Projects\Project2.doc",FileMode.Create, FileAccess.Write);

Writing a File

Both WriteByte() and Write() return void.

1.

// as above but other streams don't get access to the file while fs3 is open FileStream fs3 = new FileStream(@"C:\C# Projects\Project3.doc", FileMode.Create, FileAccess.Write, FileShare.None); Of course, after youve finished with a stream, you should close it: fs.Close(); ReadByte () grabs 1 byte from the stream and casts the result to an int that has a value between 0 and 255. If you have reached the end of the stream, it returns -1: int NextByte = fs.ReadByte(); Read() method reads a specified number of bytes into an array. Read() returns the number of bytes actually read - if this value is zero, you know that youre at the end of the stream. WriteByte() writes a single byte to the stream: byte NextByte = 100; fs.WriteByte(NextByte); Write(), on the other hand, writes out an array of bytes. For instance, if you initialized the ByteArray mentioned before with some values, you could use the following code to write out the first nBytes of the array: fs.Write(ByteArray, 0, nBytes); The second parameter to Write() is an offset.

2.

3.
int nBytesRead = fs.Read(ByteArray, 0, nBytes); The second parameter to Read() is an offset.

3) Done through the StreamReader and StreamWriter classes


If you know that a particular file contains text, you will usually find it more convenient to read and write it using the StreamReader and StreamWriter classes instead of the FileStream class. Thats because these classes work at a slightly higher level and are specifically geared to reading and writing text. The methods that they implement are able to automatically detect where convenient points to stop reading text are, based on the contents of the stream. By using the StreamReader and StreamWriter classes you dont need to worry about the encoding (the text format) used in the file.

Sr. No.

Reading a File

Writing a File
StreamWriter sWriter = new StreamWriter(@"C:\ReadMe.txt");

StreamReader sReader = new StreamReader(@"C:\ReadMe.txt"); Alternatively, if you prefer to specify that UTF8 encoding should be assumed: StreamReader sReader = new StreamReader(@"C:\ReadMe.txt", Encoding.UTF8);

Alternatively, if you prefer to specify that ASCII encoding should be assumed: StreamWriter sWriter = new StreamWriter(@"C:\ReadMe.txt", true, Encoding.ASCII); In this constructor, the second parameter is a Boolean that indicates whether the file should be opened for appending. You may want to hook up StreamWriter to a file stream to give you more control over the options for opening the file: FileStream fs = new FileStream(@"C:\ReadMe.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read); StreamWriter sw = new StreamWriter(fs); FileStream does not implement any methods that return a StreamWriter class. Just as with all other stream classes, it is important to close a StreamWriter class when you have finished with it: sw.Close();

1.

The following example demonstrates hooking up a StreamReader to a FileStream. The advantage of this is that you can specify whether to create the file and the share permissions, which you cannot do if you directly attach a StreamReader to the file: FileStream fs = new FileStream(@"C:\ReadMe.txt", FileMode.Open, FileAccess.Read, FileShare.None); StreamReader sr = new StreamReader(fs); Just as with a FileStream, you should always close a StreamReader after use. sr.Close();

2.

The following example demonstrates a StreamReader is obtained from a FileInfo instance:

Alternatively, if you want to create a new file and start writing data to it, youll find this sequence useful: FileInfo myFile = new FileInfo(@"C:\NewFile.txt"); StreamWriter sw = myFile.CreateText(); 1. You can write line:

3.

FileInfo myFile = new FileInfo(@"C:\ReadMe.txt"); StreamReader sr = myFile.OpenText();

1. You can read line: sw .WriteLine() string nextLine = sr.ReadLine(); 2. You can write string: 2. You can grab the entire remainder of the file (or strictly, the remainder of the stream) in one string: string nextLine = "Groovy Line"; sw.Write(nextLine); 3. You can write a single character: 3. You can read a single character: int nextChar = sr.Read(); This overload of Read() casts the returned character to an int. This is so that it has the option of returning a value of -1 if the end of the stream has been reached. char nextChar = 'a'; sw.Write(nextChar); 4. You can write character array: char [] charArray = new char[100]; sw.Write(charArray);

4.

string restOfStream = sr.ReadToEnd();

5. You can write out a portion of character array : int nCharsToWrite = int startAtLocation char [] charArray = sw.Write(charArray, nCharsToWrite); 50; = 25; new char[100]; startAtLocation,

Enumerations in FileStream Objects


FileMode enumeration

FileMode Enumeration Create CreateNew

Description FileMode.Create value creates a file and if the file already exists, it will be overwritten. Creates a file and if the file already exists, an IOException is thrown. Opens the file and starts writing at the end of the file. If the file doesn't exist a file is created. Note that you can use FileMode.Append only with FileAccess.Write or an exception of type ArgumentException is thrown. Opens the file if it exists. If the file does not exist, an exception of type FileNotFoundException is thrown. Opens the file if it exists. If the file does not exist, the file will be created. Opens a file and truncates it to make it a size of zero bytes.

Append

Open OpenOrCreate Truncate The FileAccess enumeration values

FileAccess Enumeration Description Read Write ReadWrite Sets read access to the file. Sets write access to the file. Sets read/write access to the file.

FileShare enumeration provides values for how the file is shared with other streams by the running process or other process. FileShare Enumeration None Read Write ReadWrite Description Obtains an exclusive access to the file until it's closed, which means that other streams can't read from or write to the file until this stream is closed. Other streams (in the current process or in another one) can obtain read access to the file. Other streams (in the current process or in another one) can obtain write access to the file Other streams can obtain ReadWrite access to the file

Das könnte Ihnen auch gefallen