Chapter 9: Working with Files, Streams, and Serialization Flashcards

1
Q

System.IO.Directory;
can you say some useful methods of this library?

A

handle cross-platform environments
Directory.GetDirectories()
Directory.Exists()
Directory.CreateDirectory()
Directory.Delete()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

System.IO.Path
can you say some useful methods of this library?

A

Path.PathSeparator
Path.GetFullPath()
Path.Combine()
Path.GetDirectoryName()
Path.GetExtension()
Path.GetFileName()
Path.GetFileNameWithoutExtension()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

System.Environment
can you say some useful methods of this library?

A

Environment.CurrentDirectory
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Managing drives

A

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);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Managing files

A

// 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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Managing paths

A

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()}”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Getting file information

A

FileInfo info = new(backupFile);
WriteLine($”{backupFile}:”);
WriteLine($”Contains {info.Length} bytes”);
WriteLine($”Last accessed {info.LastAccessTime}”);
WriteLine($”Has readonly set to {info.IsReadOnly}”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to open a file and read from it?

A

FileStream file = File.Open(pathToFile,
FileMode.Open, FileAccess.Read, FileShare.Read);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to check a file or directory’s attributes?

A

FileInfo info = new(backupFile);
WriteLine(“Is the backup file compressed? {0}”,
info.Attributes.HasFlag(FileAttributes.Compressed));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Can you tell all of the concreate stream?

A

FileStream, MemoryStream,
BufferedStream, GZipStream, and SslStream,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the common members of the Stream class ?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to read & write plain text?

A

File.ReadAllText(textFile);
StreamWriter text = File.CreateText(textFile);
foreach (string item in Viper.Callsigns)
{
text.WriteLine(item);
}
text.Close();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to read & write xml files?

A

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));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Simplifying disposal by using the using statement

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to compress file by gzip algorithm?

A

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
}
}
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to archive contents into a tar archive?

A

using System.Formats.Tar; // TarFile

TarFile.CreateFromDirectory(
sourceDirectoryName: sourceDirectory,
destinationFileName: tarFile,
includeBaseDirectory: true);

TarFile.ExtractToDirectory(
sourceFileName: tarFile,
destinationDirectoryName: destinationDirectory,
overwriteFiles: true);

17
Q

How to encoding string as byte array

A

Encoding.UTF8.GetBytes(message);
and reverse is
Encoding.UTF8.GetString(encoded);

18
Q

How to encoding and decoding text in files?

A

StreamReader reader = new(stream, Encoding.UTF8);
StreamWriter writer = new(stream, Encoding.UTF8);

19
Q

how to reading and writing with random access handles

A

using Microsoft.Win32.SafeHandles; // SafeFileHandle
using System.Text; // Encoding
using SafeFileHandle handle =
File.OpenHandle(path: “coffee.txt”,
mode: FileMode.OpenOrCreate,
access: FileAccess.ReadWrite);

string message = “Café £4.39”;
ReadOnlyMemory<byte> buffer = new(Encoding.UTF8.GetBytes(message));
await RandomAccess.WriteAsync(handle, buffer, fileOffset: 0);
long length = RandomAccess.GetLength(handle);
Memory<byte> contentBytes = new(new byte[length]);
await RandomAccess.ReadAsync(handle, contentBytes, fileOffset: 0);
string content = Encoding.UTF8.GetString(contentBytes.ToArray());
WriteLine($"Content of file: {content}");</byte></byte>

20
Q

How to serializing as XML

A

using System.Xml.Serialization;
XmlSerializer xs = new(type: people.GetType());
string path = Combine(CurrentDirectory, “people.xml”);
using (FileStream stream = File.Create(path))
{
xs.Serialize(stream, people);
}

21
Q

How to generating compact XML?

A

[XmlAttribute(“fname”)]
public string? FirstName { get; set; }
[XmlAttribute(“lname”)]
public string? LastName { get; set; }
[XmlAttribute(“dob”)]
public DateTime DateOfBirth { get; set; }

22
Q

How to deserializing XML files?

A

using (FileStream xmlLoad = File.Open(path, FileMode.Open))
{
// deserialize and cast the object graph into a List of Person
List<Person>? loadedPeople =
xs.Deserialize(xmlLoad) as List<Person>;
if (loadedPeople is not null)
{
foreach (Person p in loadedPeople)
{
WriteLine("{0} has {1} children.",
p.LastName, p.Children?.Count ?? 0);
}
}
}</Person></Person>

23
Q

How to serializing & deserializing with json (Newtonsoft.Json)?

A

Newtonsoft.Json.JsonSerializer.Serialize(jsonStream, people);
Newtonsoft.Json.JsonSerializer.Deserialize(jsonStream, people);c

24
Q

How to use
System.Text.Json.JsonSerializer

A

List<Person>? loadedPeople =
await System.Text.Json.JsonSerializer.DeserializeAsync(utf8Json: jsonLoad,
returnType: typeof(List<Person>)) as List<Person>;</Person></Person></Person>

25
Q

How to controlling JSON processing?

A
  • Including and excluding fields.
    [JsonInclude] // include this field
    public DateTime PublishDate;
  • Setting a casing policy.
  • Selecting a case-sensitivity policy.
  • Choosing between compact and prettified whitespace
    JsonSerializerOptions options = new()
    {
    IncludeFields = true, // includes all fields
    PropertyNameCaseInsensitive = true,
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    };