Files in C# Programming

HottestGenre avatar
HottestGenre
·
·
Download

Start Quiz

Study Flashcards

19 Questions

Which class provides static methods for creating, copying, deleting, moving, and opening files?

File

StreamWriter is used for reading characters from a byte stream.

False

What is the smallest data item that computers support?

bit

What is a group of related fields that contain data about an entity called?

Record

What method is used to close the current StreamWriter?

Close()

Each record in a sequential access file is read based on its relative position.

True

The exception that is thrown when a file that does not exist on disk is accessed is ____________.

FileNotFoundException

Match the StreamReader and StreamWriter members with their descriptions:

Close() = Closes the current StreamWriter ReadLine() = Reads a line of characters from the current stream and returns the data as a string WriteLine() = Writes the characters to the stream, followed by a line terminator

C# considers characters to be composed of __ bytes in the Unicode character set.

2

Match the following stream types with their descriptions:

Base Streams = Read and write data from and to an external data storage mechanism. Pass-through Streams = Read from and write to other streams, adding additional functionality like buffering, encoding, and compression.

What class provides functionality for working with paths in C#?

System.IO.Path

What does the DirectoryInfo object returned by method CreateDirectory contain information about?

Parent and root directory

Serialization is the process of converting objects into streams of bytes in C#.

True

The ________ class enables entire objects to be written to or read from a stream.

BinaryFormatter

Which classes are used for handling binary files in C#?

FileStream and BinaryWriter

Can binary files be opened and read directly using Notepad?

False

What is the purpose of the BinaryReader class in C#?

to read binary data from files

Match the following file handling classes with their functionalities:

BinaryWriter = Writing binary data to files File = Accessing information about files Directory = Manipulating directories and folders BinaryReader = Reading binary data from files

The Static Member __________ in the File class appends the specified string to the file.

AppendAllText()

Study Notes

Files in C#

  • 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 is often called persistent data.
  • Computers store files on secondary storage devices, such as magnetic disks, optical disks, flash memory, and magnetic tapes.

Data Hierarchy

  • The smallest data item that computers support is called a bit (short for “binary digit”—a digit that can assume one of two values).
  • Digits, letters, and special symbols are referred to as characters.
  • Bytes are composed of eight bits.
  • C# uses the Unicode character set (http://www.unicode.org) in which characters 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.
  • Data items processed by computers form a data hierarchy, in which data items become larger and more complex in structure.

Data Hierarchy (Continued)

  • A record is a collection of related fields that contain data about an entity.
  • A file is a group of related records.
  • To facilitate the retrieval of specific records from a file, at least one field in each record is chosen as a record key, which uniquely identifies a record.
  • A common file organization is called a sequential file, in which records typically are stored in order by a record-key field.
  • A group of related files often are stored in 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.
  • When a file is opened, an object is created and a stream is associated with the object.

Random Access File

  • Records are not in any sequence and can be accessed in any order.
  • A C# application opens a file by creating an object and associating a stream of bytes with that object.
  • When you finish using a file, the program should close the file.
  • Not closing a file may make it inaccessible.
  • Not closing an output file can result in data not being written to the file.

Files and the File and Directory Classes

  • Folder or Directory: A location inside the root directory designed to group items or files that are similar in nature.
  • Path: A combination of the disk drive plus the complete hierarchy of directories in which a file resides.
  • Example: C:\C#\Chapter.07\Data.txt
  • C# provides built-in classes named File and Directory.
  • Contain methods to help you manipulate files and their directories.
  • Access information about files.
  • Create, delete, or move files.

Enumerations

  • Enumeration - special form of value type that supplies alternate names for the values of an underlying primitive type.
  • Enumeration type has a name and a set of fields.
  • Example: public enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
  • GetAttributes() returns an enumeration.
  • Enumerated values for FileAttributes include Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, ReadOnly, and System.
  • Using enumerations makes coding simpler and the output more readable.

Streams

  • Stream: Functions as a pipeline or channel between an input device and an application, and potentially an output device.
  • Base Streams: Read and write data from and to an external data storage mechanism.
  • Pass-through Streams: Read from and write to other streams, adding additional functionality (e.g. buffering, encoding, and compression).
  • Examples: FileStream, MemoryStream, NetworkStream, BufferedStream, CryptoStream.

Main Operations with Streams

  • Construct (Create): The stream connects to the data transfer/storage mechanism or to another stream.
  • Reading: Data is retrieved from the stream.
  • Writing: Data is sent to the stream.
  • Positioning: Moves the current stream position (if positioning is supported).
  • Closure: The work on the stream is completed and the used resources are released.

Base Class for Streams

  • The base class for all streams is the System.IO.Stream abstract class.
  • It defines methods for performing basic operations.
  • Not all streams support read, write, and position operations.
  • Which operations are supported can be checked using the CanRead, CanWrite, and CanSeek properties.
  • Streams that allow positioning support Position and Length properties.
  • There is a special Stream.Null stream that ignores all read and write attempts.

Files and Streams (Continued)

  • When a console application executes, the runtime environment creates the Console.Out, Console.In, and Console.Error streams.
  • Console.In refers to the standard input stream object, which enables a program to input data from the keyboard.
  • Console.Out refers to the standard output stream object, which enables a program to output data to the screen.
  • Console.Error refers to the standard error stream object, which enables a program to output error messages to the screen.

Files and Streams (Continued)

  • The System.IO namespace includes stream classes such as StreamReader, StreamWriter, and FileStream for file input and output.
  • These stream classes inherit from abstract classes TextReader, TextWriter, and Stream, respectively.
  • Abstract class Stream provides functionality for representing streams as bytes.
  • Classes FileStream, MemoryStream, and BufferedStream (all from namespace System.IO) inherit from class Stream.

Files and Streams (Continued)

  • Class FileStream can be used to write data to and read data from files.
  • FileStream is used alone for bytes and with either StreamReader and StreamWriter for text, for either input from and output to a file.
  • StreamWriter class for writing data to text file.
  • Includes implementations for Write() and WriteLine().
  • StreamReader class to read or write to or from text files.
  • Includes implementations of Read() and ReadLine().

System.IO Classes

  • Class Description
  • BinaryReader Reads primitive data types as binary values
  • BinaryWriter Writes primitive types in binary to a stream
  • Directory Exposes static methods for creating and moving through directories and subdirectories
  • DirectoryInfo Exposes instance methods for creating and moving through directories and subdirectories
  • DirectoryNotFoundException The exception that is thrown when part of a file or directory cannot be found
  • EndOfStreamException The exception that is thrown when reading is attempted past the end of a stream

System.IO Classes (Continued)

  • Class Description
  • File Provides static methods for creating, copying, deleting, moving, and opening files, and aids in the creation of FileStream objects
  • FileInfo Provides instance methods for creating, copying, deleting, moving, and opening files, and aids in the creation of FileStream objects
  • FileLoadException The exception that is thrown when a file is found but cannot be loaded
  • FileNotFoundException The exception that is thrown when an attempt to access a file that does not exist on disk fails
  • FileStream Exposes a stream around a file, supporting both synchronous and asynchronous read and write operations

Readers and Writers

  • Classes that make it easier to work with streams.
  • Allow reading and writing various data structures, such as primitive types, text information, and other types.
  • Can be binary or text.
  • TextReader and TextWriter Classes:
    • Abstract classes not used directly.
    • StreamReader - reads text data from a stream.
    • StringReader - reads text data from a string.
    • StreamWriter – writes text data to a stream.
    • StringWriter - writes text data to a string, uses StringBuilder internally.
  • BinaryReader and BinaryWriter Classes:
    • Provide reading and writing of primitive data types in binary form.
    • Methods: ReadChar(), ReadChars(), ReadInt32(), ReadDouble(),...
    • Methods: Write(char), Write(char[]), Write(Int32), Write(Double),...
    • Allow reading and writing a string by writing it as an array of characters preceded by its length: ReadString(), Write(string)

File Streams (Continued)

  • System.IO namespace must be imported for files: using System.IO;
  • The bin\Debug or bin\Release subdirectory of the current project is used for file when you don’t specify a path.
  • Use verbatim string character (@) or escape sequence (\) to specify path:
    • @"C:\CSharpProjects\Proj1" or "c:\CSharpProjects\Proj1"

File Streams (Continued)

  • Several abstract classes for dealing with files:
    • Stream, TextWriter, and TextReader
  • Stream classes provide generic methods for dealing with input/output
  • IO.Stream class and its subclasses – byte-level data
  • IO.TextWriter and IO.TextReader – data in a text (readable) format
  • StreamReader and StreamWriter derived classes of IO.TextWriter and IO.TextReader

File Streams (Continued)

  • StreamWriter outputFile = new StreamWriter("someOutputFileName");
  • StreamReader inputFile = new StreamReader("someInputFileName");
  • outputFile and inputFile represent the file stream objects
  • Actual file names are "someOutputFileName" and "someInputFileName" – inside double quotes
  • Place file extensions such as .dat, .dta, or .txt onto the end of actual filename when it is created

File Streams (Continued)

  • Use Write() or WriteLine() with the instantiated stream object:
    • outputFile.WriteLine("This is the first line in a text file");
  • Use Read() or ReadLine() with the instantiated stream object:
    • string inValue = inputFile.ReadLine();### FileStream Class
  • The FileStream class is used to work with file streams and supports reading, writing, and positioning (if the device where the file is located supports these operations).
  • The FileStream class inherits from the Stream class and supports all of its methods and properties.
  • In its constructor, it is set:
    • File name
    • Way to open the file (FileMode)
    • Access mode (FileAccess)
    • Access for competing users (FileShare)

FileMode

  • File opening mode:
    • Open
    • Append
    • Create
    • CreateNew
    • OpenOrCreate
    • Truncate

FileAccess

  • File access mode:
    • Read
    • Write
    • ReadWrite

FileShare

  • Access mode for other users while we keep the file open:
    • None
    • Read
    • Write
    • ReadWrite

BinaryReader and BinaryWriter Classes

  • Used for writing and reading binary data, rather than character strings.
  • Files created are readable by the computer, but not by Notepad.
  • A program is needed to interpret the file contents.

BinaryWriter Class

  • Instantiates an object of the FileStream and BinaryWriter classes.
  • FileStream filStream;
  • BinaryWriter binWriter;
  • BinaryWriter object is wrapped around the FileStream object.

BinaryReader Class

  • Cannot simply open a binary file in Notepad and view its contents.
  • Need to write program statements that use the BinaryReader class to retrieve the results.
  • Three different read methods were invoked to read data from the file:
    • ReadInt32()
    • ReadDecimal()
    • ReadString()

File and Directory Classes

  • File class:
    • Contains methods to access information about files.
    • Contained in the System.IO namespace.
  • Directory class:
    • Provides information about directories or folders.

File and FileInfo Classes

  • File class:
    • Provides functionality to:
      • Create file
      • Open a file
      • Copy file
      • Move (rename) a file
      • Delete file
      • Extract the time of last access and modification
      • Existence check
    • The File class provides these methods statically.
  • FileInfo class:
    • Provides functionality to:
      • Create file
      • Open a file
      • Copy file
      • Move (rename) a file
      • Delete file
      • Extract the time of last access and modification
      • Existence check
    • The FileInfo class provides these methods by instance.

Directory and DirectoryInfo Classes

  • Directory class:
    • Provides functionality to:
      • Create directories and subdirectories
      • Retrieve all files
      • Retrieve all subdirectories
      • Move (rename)
      • Delete
      • Extract the parent directory
      • Existence check
      • Extract the full name
    • The Directory class provides these methods statically.
  • DirectoryInfo class:
    • Provides functionality to:
      • Create directories and subdirectories
      • Retrieve all files
      • Retrieve all subdirectories
      • Move (rename)
      • Delete
      • Extract the parent directory
      • Existence check
      • Extract the full name
    • The DirectoryInfo class provides these methods by instance.

Path Class

  • The System.IO.Path class provides functionality for working with paths.
  • More important properties and methods:
    • DirectorySeparatorChar
    • Combine(...)
    • GetExtension(...)
    • GetFileName(...)
    • GetTempFileName(...)### Environment Special Folders
  • Environment.SpecialFolder.MyDocuments returns the path to the My Documents folder.
  • Environment.SpecialFolder.DesktopDirectory returns the path to the Desktop folder.
  • Environment.SpecialFolder.Favorites returns the path to the Favorites folder.

Disadvantages of Text Files

  • Data in text files is easily readable and not secure.
  • Converting each field to text and combining fields with delimiters can be cumbersome.

Serialization and Deserialization

  • Serialization is the process of converting objects into streams of bytes.
  • Deserialization is the process of converting streams of bytes back into objects.

Object Serialization in C#

  • Object serialization allows entire objects to be written to or read from a file.
  • Serialized objects can be read from a file and deserialized.

BinaryFormatter Class

  • The BinaryFormatter class enables entire objects to be written to or read from a stream.
  • The Serialize method writes an object's representation to a file.
  • The Deserialize method reads this representation from a file and reconstructs the original object.

Serializable Class Requirements

  • A class marked with the [Serializable] attribute must have all instance variables that are also serializable.
  • By default, all C# simple data types are serializable, including strings.
  • If a class contains fields that are more complex data types, you must check the declaration of those classes to ensure they are serializable.

Serialization Example

  • A serializable class can be written to a file using the BinaryFormatter class.
  • The serialized object can be read from the file and deserialized using the BinaryFormatter class.

Creating a Sequential-Access File Using Object Serialization

  • The classes for objects that we wish to serialize must include the [Serializable] attribute in their declarations or must implement interface ISerializable.
  • In a serializable class, you must ensure that every instance variable of the class is also serializable.
  • Array objects are serializable by default, but if the array contains references to other objects, those objects may or may not be serializable.

This quiz covers the basics of working with files in C# programming, including data storage and retrieval. Learn about persistent data and how computers store files on secondary storage devices.

Make Your Own Quizzes and Flashcards

Convert your notes into interactive study material.

Get started for free
Use Quizgecko on...
Browser
Browser