Inno 3.8 Streams Flashcards
(33 cards)
What is the purpose of the Stream class in .NET?
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 does FileStream work?
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.
What is MemoryStream used for?
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.
What is the role of BufferedStream?
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.
What are StreamReader and StreamWriter used for?
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 do you read all text from a file using StreamReader?
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();
What classes are used to manipulate files and directories?
.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 do you check if a file or directory exists?
Use File.Exists(path) and Directory.Exists(path) to verify the existence of files or directories before performing operations to avoid exceptions.
What is serialization in .NET and why is it useful?
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 does BinaryFormatter work and should it be used today?
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.
What is XmlSerializer and when should you use it?
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);
What is System.Text.Json and why is it preferred for JSON in .NET?
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>
When would you use Newtonsoft.Json (Json.NET) instead of System.Text.Json?
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 do you implement custom serialization using ISerializable?
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); } }
What is async file I/O and why is it important?
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 do you asynchronously write to a file in .NET?
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);
How do you asynchronously read a file line-by-line?
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);
}
What precautions should you take when using async file I/O?
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.
How do you efficiently read a large file in .NET?
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.
What is file buffering and how does it help?
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.
How can you read a file in chunks using FileStream?
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]
}
How can you process a large file with an offset-based approach?
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);
How can you split a large file into chunks for processing or uploading?
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.
What is the purpose of the FileSecurity and AccessControl classes?
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.