Chapter 9: Working with Files, Streams, and Serialization Flashcards
System.IO.Directory;
can you say some useful methods of this library?
handle cross-platform environments
Directory.GetDirectories()
Directory.Exists()
Directory.CreateDirectory()
Directory.Delete()
System.IO.Path
can you say some useful methods of this library?
Path.PathSeparator
Path.GetFullPath()
Path.Combine()
Path.GetDirectoryName()
Path.GetExtension()
Path.GetFileName()
Path.GetFileNameWithoutExtension()
System.Environment
can you say some useful methods of this library?
Environment.CurrentDirectory
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Managing drives
oreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady)
{
WriteLine(
“{0,-30} | {1,-10} | {2,-7} | {3,18:N0} | {4,18:N0}”,
drive.Name, drive.DriveType, drive.DriveFormat,
drive.TotalSize, drive.AvailableFreeSpace);
}
else
{
WriteLine(“{0,-30} | {1,-10}”, drive.Name, drive.DriveType);
}
}
Managing files
// define a directory path to output files
// starting in the user’s folder
string dir = Combine(
GetFolderPath(SpecialFolder.Personal), “OutputFiles”);
CreateDirectory(dir);
// define file paths
string textFile = Combine(dir, “Dummy.txt”);
string backupFile = Combine(dir, “Dummy.bak”);
WriteLine($”Working with: {textFile}”);
// check if a file exists
WriteLine($”Does it exist? {File.Exists(textFile)}”);
// create a new text file and write a line to it
StreamWriter textWriter = File.CreateText(textFile);
textWriter.WriteLine(“Hello, C#!”);
textWriter.Close(); // close file and release resources
WriteLine($”Does it exist? {File.Exists(textFile)}”);
// copy the file, and overwrite if it already exists
File.Copy(sourceFileName: textFile,
destFileName: backupFile, overwrite: true);
WriteLine(
$”Does {backupFile} exist? {File.Exists(backupFile)}”);
Write(“Confirm the files exist, and then press ENTER: “);
ReadLine();
// delete file
File.Delete(textFile);
WriteLine($”Does it exist? {File.Exists(textFile)}”);
// read from the text file backup
WriteLine($”Reading contents of {backupFile}:”);
StreamReader textReader = File.OpenText(backupFile);
WriteLine(textReader.ReadToEnd());
textReader.Close()
Managing paths
WriteLine($”Folder Name: {GetDirectoryName(textFile)}”);
WriteLine($”File Name: {GetFileName(textFile)}”);
WriteLine(“File Name without Extension: {0}”,
GetFileNameWithoutExtension(textFile));
WriteLine($”File Extension: {GetExtension(textFile)}”);
WriteLine($”Random File Name: {GetRandomFileName()}”);
WriteLine($”Temporary File Name: {GetTempFileName()}”);
Getting file information
FileInfo info = new(backupFile);
WriteLine($”{backupFile}:”);
WriteLine($”Contains {info.Length} bytes”);
WriteLine($”Last accessed {info.LastAccessTime}”);
WriteLine($”Has readonly set to {info.IsReadOnly}”);
How to open a file and read from it?
FileStream file = File.Open(pathToFile,
FileMode.Open, FileAccess.Read, FileShare.Read);
How to check a file or directory’s attributes?
FileInfo info = new(backupFile);
WriteLine(“Is the backup file compressed? {0}”,
info.Attributes.HasFlag(FileAttributes.Compressed));
Can you tell all of the concreate stream?
FileStream, MemoryStream,
BufferedStream, GZipStream, and SslStream,
What are the common members of the Stream class ?
CanRead,
CanWrite
These properties determine if you can read from and write to the stream.
Length, Position
These properties determine the total number of bytes and the current position
within the stream. These properties may throw an exception for some types of
streams.
Dispose This method closes the stream and releases its resources.
Flush If the stream has a buffer, then this method writes the bytes in the buffer to the
stream and the buffer is cleared.
CanSeek This property determines if the Seek method can be used.
Seek This method moves the current position to the one specified in its parameter.
Read, ReadAsync
These methods read a specified number of bytes from the stream into a byte
array and advance the position.
ReadByte This method reads the next byte from the stream and advances the position.
Write,
WriteAsync
These methods write the contents of a byte array into the stream.
WriteByte This method writes a byte to the stream.
How to read & write plain text?
File.ReadAllText(textFile);
StreamWriter text = File.CreateText(textFile);
foreach (string item in Viper.Callsigns)
{
text.WriteLine(item);
}
text.Close();
How to read & write xml files?
string xmlFile = Combine(CurrentDirectory, “streams.xml”);
FileStream? xmlFileStream = null;
XmlWriter? xml = null;
try
{
xmlFileStream = File.Create(xmlFile);
xml = XmlWriter.Create(xmlFileStream,
new XmlWriterSettings { Indent = true });
xml.WriteStartDocument();
xml.WriteStartElement(“callsigns”);
foreach (string item in Viper.Callsigns)
{
xml.WriteElementString(“callsign”, item);
}
xml.WriteEndElement();
xml.Close();
xmlFileStream.Close();
}
catch (Exception ex)
{
WriteLine($”{ex.GetType()} says {ex.Message}”);
}
finally
{
if (xml != null)
{
xml.Dispose();
WriteLine(“The XML writer’s unmanaged resources have been
disposed.”);
}
if (xmlFileStream != null)
{
xmlFileStream.Dispose();
WriteLine(“The file stream’s unmanaged resources have been
disposed.”);
}
}
WriteLine(“{0} contains {1:N0} bytes.”,
arg0: xmlFile,
arg1: new FileInfo(xmlFile).Length);
WriteLine(File.ReadAllText(xmlFile));
Simplifying disposal by using the using statement
using (FileStream file2 = File.OpenWrite(
Path.Combine(path, “file2.txt”)))
{
using (StreamWriter writer2 = new StreamWriter(file2))
{
try
{
writer2.WriteLine(“Welcome, .NET!”);
}
catch (Exception ex)
{
WriteLine($”{ex.GetType()} says {ex.Message}”);
}
} // automatically calls Dispose if the object is not null
}
How to compress file by gzip algorithm?
static void Compress(string algorithm = “gzip”)
{
// define a file path using algorithm as file extension
string filePath = Combine(
CurrentDirectory, $”streams.{algorithm}”);
FileStream file = File.Create(filePath);
Stream compressor;
if (algorithm == “gzip”)
{
compressor = new GZipStream(file, CompressionMode.Compress);
}
else
{
compressor = new BrotliStream(file, CompressionMode.Compress);
}
using (compressor)
{
using (XmlWriter xml = XmlWriter.Create(compressor))
{
xml.WriteStartDocument();
xml.WriteStartElement(“callsigns”);
foreach (string item in Viper.Callsigns)
{
xml.WriteElementString(“callsign”, item);
}
}
}
Stream decompressor;
if (algorithm == “gzip”)
{
decompressor = new GZipStream(
file, CompressionMode.Decompress);
}
else
{
decompressor = new BrotliStream(
file, CompressionMode.Decompress);
}
using (decompressor)
using (XmlReader reader = XmlReader.Create(decompressor))
while (reader.Read())
{
// check if we are on an element node named callsign
if ((reader.NodeType == XmlNodeType.Element)
&& (reader.Name == “callsign”))
{
reader.Read(); // move to the text inside element
WriteLine($”{reader.Value}”); // read its value
}
}
}
}