Inno 3.8 Streams Flashcards

(33 cards)

1
Q

What is the purpose of the Stream class in .NET?

A

Stream is an abstract base class that defines a sequence of bytes and provides a generic view of data sources and sinks.

It is the foundation for reading and writing data to files, memory, network, and other I/O sources. Derived classes include FileStream, MemoryStream, NetworkStream, and others.

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

How does FileStream work?

A

FileStream is used to read from and write to files on disk. It supports both synchronous and asynchronous operations and provides methods like Read, Write, Seek, and Flush. It operates on byte-level data and is suitable for both binary and text file processing.

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

What is MemoryStream used for?

A

MemoryStream allows reading and writing data to memory instead of a physical file. It’s useful for scenarios like caching, creating temporary buffers, or manipulating data before saving to a file. Since it’s in-memory, it offers fast access and no disk I/O.

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

What is the role of BufferedStream?

A

BufferedStream wraps another stream (like FileStream) to improve read and write performance by using an internal buffer.

This reduces the number of I/O operations by accumulating data in memory before writing to or reading from the underlying stream.

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

What are StreamReader and StreamWriter used for?

A

StreamReader and StreamWriter are designed for reading and writing characters (text) to streams using a specific encoding. They simplify handling text files and support both line-by-line and character-based operations.

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

How do you read all text from a file using StreamReader?

A

You can use StreamReader.ReadToEnd() to read the entire contents of a text file.

using var reader = new StreamReader(“file.txt”);
string content = reader.ReadToEnd();

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

What classes are used to manipulate files and directories?

A

.NET provides static classes like File, Directory, and Path. File and Directory offer methods to create, delete, move, and query files/directories. Path provides utilities for manipulating file and directory paths.

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

How do you check if a file or directory exists?

A

Use File.Exists(path) and Directory.Exists(path) to verify the existence of files or directories before performing operations to avoid exceptions.

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

What is serialization in .NET and why is it useful?

A

Serialization is the process of converting an object into a format that can be stored (e.g., to a file or memory) or transmitted (e.g., over a network).

The most common formats include binary, XML, and JSON. It’s useful for persisting object state or communicating between services. .NET provides multiple serializers, each suited to different scenarios based on performance, readability, and compatibility.

CONVERTING AN OBJECT INTO FORMAT THAT CAN BE STORED OR TRANSMITTED

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

How does BinaryFormatter work and should it be used today?

A

BinaryFormatter serializes objects into a compact binary format. It was widely used in early .NET versions for saving and loading object graphs. However, it is obsolete and insecure and should no longer be used. Microsoft recommends avoiding it due to remote code execution vulnerabilities and instead using safer serializers like System.Text.Json or XmlSerializer.

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

What is XmlSerializer and when should you use it?

A

XmlSerializer converts objects to and from XML format. It is ideal when you need human-readable output or interoperability with other systems that consume XML. You must have a parameterless constructor, and only public properties and fields are serialized unless explicitly ignored.
Example:

var serializer = new XmlSerializer(typeof(MyClass));
serializer.Serialize(stream, myObject);

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

What is System.Text.Json and why is it preferred for JSON in .NET?

A

System.Text.Json is a high-performance JSON serializer introduced in .NET Core 3. It’s faster and more memory-efficient than Newtonsoft.Json for most use cases. It supports serialization, deserialization, custom converters, and works well with Span<T> for large payloads.</T>

string json = JsonSerializer.Serialize(myObject);
var obj = JsonSerializer.Deserialize<MyClass>(json);</MyClass>

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

When would you use Newtonsoft.Json (Json.NET) instead of System.Text.Json?

A

Use Newtonsoft.Json when you need advanced features like polymorphic deserialization, flexible contract resolvers, or working with dynamic/anonymous types. It’s more feature-rich and battle-tested, though slightly slower. It remains widely used, especially in legacy .NET Framework projects.

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

How do you implement custom serialization using ISerializable?

A

Implement the ISerializable interface to control exactly how your object is serialized. This is useful for advanced cases, like conditional field inclusion or supporting multiple versions. You must provide a special constructor that takes SerializationInfo and StreamingContext, and implement GetObjectData.

[Serializable]
class MyData : ISerializable {
public string Name;

protected MyData(SerializationInfo info, StreamingContext context) {
    Name = info.GetString("Name");
}

public void GetObjectData(SerializationInfo info, StreamingContext context) {
    info.AddValue("Name", Name);
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is async file I/O and why is it important?

A

Async file I/O allows non-blocking read and write operations, which is essential in responsive UIs and scalable servers. Methods like ReadAsync and WriteAsync let threads continue working while waiting for the I/O to complete, improving overall performance and responsiveness, especially for large files or high concurrency.

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

How do you asynchronously write to a file in .NET?

A

Use FileStream.WriteAsync or StreamWriter.WriteAsync inside an async method. Ensure the stream is opened with useAsync: true for optimal performance.

using var stream = new FileStream(“log.txt”, FileMode.Append, FileAccess.Write, FileShare.None, 4096, useAsync: true);
using var writer = new StreamWriter(stream);
await writer.WriteLineAsync(“Log entry at “ + DateTime.Now);

17
Q

How do you asynchronously read a file line-by-line?

A

Use StreamReader.ReadLineAsync() in a loop, which lets you process large text files without loading everything into memory.

using var reader = new StreamReader(“data.txt”);
string? line;
while ((line = await reader.ReadLineAsync()) != null) {
Console.WriteLine(line);
}

18
Q

What precautions should you take when using async file I/O?

A

Ensure the underlying stream supports async operations (useAsync: true), avoid blocking calls like .Result or .Wait(), and consider using ConfigureAwait(false) in libraries. Also, manage exceptions properly, especially IOException, which can occur if the file is in use or access is denied.

19
Q

How do you efficiently read a large file in .NET?

A

To read large files efficiently, avoid loading the entire file into memory. Instead, use a buffered approach—read the file in chunks or line-by-line using StreamReader or FileStream with a buffer.

This reduces memory usage and improves performance on large datasets.

20
Q

What is file buffering and how does it help?

A

Buffering minimizes direct I/O operations by storing data temporarily in memory. For example, BufferedStream wraps another stream and buffers reads/writes, reducing system calls. It’s especially helpful when working with network or disk files, where access is relatively slow compared to memory.

21
Q

How can you read a file in chunks using FileStream?

A

You can use a fixed-size byte array and read repeatedly until reaching the end of the stream.

byte[] buffer = new byte[8192];
int bytesRead;
using var fs = new FileStream(“largefile.dat”, FileMode.Open);
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
// Process buffer[0..bytesRead]
}

22
Q

How can you process a large file with an offset-based approach?

A

Use FileStream.Seek() to skip to specific offsets—useful in scenarios like file resuming, skipping headers, or multi-threaded chunking.

fs.Seek(offset, SeekOrigin.Begin);
fs.Read(buffer, 0, buffer.Length);

23
Q

How can you split a large file into chunks for processing or uploading?

A

Read the file in fixed-sized byte chunks and save each to a temporary file. This is often done in scenarios like file uploading, data import/export, or parallel processing. You can later recombine the chunks or process them independently.

24
Q

What is the purpose of the FileSecurity and AccessControl classes?

A

These classes are used to programmatically manage Windows file system permissions (ACLs). You can read, modify, or set file access rules for users and groups. This allows fine-grained control over who can read, write, or delete files.

25
How do you retrieve and modify file permissions in .NET?
Use File.GetAccessControl and File.SetAccessControl along with FileSystemAccessRule. var fileSecurity = File.GetAccessControl("test.txt"); fileSecurity.AddAccessRule(new FileSystemAccessRule("DOMAIN\\User", FileSystemRights.Read, AccessControlType.Allow)); File.SetAccessControl("test.txt", fileSecurity);
26
What is UnauthorizedAccessException and when does it occur?
This exception is thrown when you attempt to access a file or directory without proper permissions. Common causes include missing write access, trying to write to read-only files, or accessing files locked by another process. Handle it with try-catch and proper user permission checks.
27
What is an IOException and how do you handle it?
An IOException indicates an I/O error has occurred, such as file not found, disk full, or file locked. Always wrap I/O code in try-catch blocks and provide user-friendly messages or retries. try { File.Copy("source.txt", "dest.txt"); } catch (IOException ex) { Console.WriteLine("Error: " + ex.Message); }
28
How can you prevent security risks when working with file paths and user input?
Validate file paths to avoid path traversal vulnerabilities. Never concatenate raw user input into file paths. Use Path.GetFullPath to resolve and verify access to only allowed directories, and consider using a whitelist of allowed directories or file extensions.
29
How do you compress data using GZipStream?
**GZipStream allows you to compress data as it's being written to a stream. To compress a file, wrap a FileStream with GZipStream in write mode.** using (var inputFile = new FileStream("input.txt", FileMode.Open)) using (var outputFile = new FileStream("compressed.gz", FileMode.Create)) using (var gzipStream = new GZipStream(outputFile, CompressionMode.Compress)) { inputFile.CopyTo(gzipStream); }
30
How do you decompress data using GZipStream?
To decompress data, you use GZipStream in Decompress mode. Here's how to read from a .gz file and extract its contents. using (var inputFile = new FileStream("compressed.gz", FileMode.Open)) using (var outputFile = new FileStream("decompressed.txt", FileMode.Create)) using (var gzipStream = new GZipStream(inputFile, CompressionMode.Decompress)) { gzipStream.CopyTo(outputFile); }
31
How do you work with ZIP files using ZipFile class?
The ZipFile class provides easy methods for creating and extracting .zip files. You can zip a folder or extract files with methods like CreateFromDirectory and ExtractToDirectory. // Compress folder to a ZIP file ZipFile.CreateFromDirectory("sourceDirectory", "archive.zip"); // Extract ZIP file contents ZipFile.ExtractToDirectory("archive.zip", "destinationFolder");
32
How can you compress multiple files into a single ZIP archive?
Use ZipArchive to add multiple files to a ZIP archive programmatically. This provides control over file entries within the archive. using (var archive = ZipFile.Open("archive.zip", ZipArchiveMode.Create)) { archive.CreateEntryFromFile("file1.txt", "file1.txt"); archive.CreateEntryFromFile("file2.txt", "file2.txt"); }
33
What are the performance considerations when using GZipStream and ZipFile?
While GZipStream and ZipFile provide effective compression, they come with trade-offs, particularly in terms of CPU usage and I/O performance. For large files, consider buffering and chunking to avoid memory issues. Additionally, using compression levels can impact performance—higher compression reduces file size but requires more CPU time.