optimizing-io-operations
Optimizes standard I/O and file operations for high-performance data processing in .NET. Use when building high-throughput file processing or competitive programming solutions.
What this skill does
# .NET High-Performance I/O
A guide for APIs optimizing large-scale data input/output.
**Quick Reference:** See [QUICKREF.md](QUICKREF.md) for essential patterns at a glance.
## 1. Core APIs
| API | Purpose |
|-----|---------|
| `Console.OpenStandardInput()` | Buffered stream input |
| `Console.OpenStandardOutput()` | Buffered stream output |
| `BufferedStream` | Stream buffering |
| `FileOptions.Asynchronous` | Async file I/O |
---
## 2. High-Speed Standard I/O
### 2.1 Basic Pattern
```csharp
// Use buffer stream directly for large I/O
using var inputStream = Console.OpenStandardInput();
using var outputStream = Console.OpenStandardOutput();
using var reader = new StreamReader(inputStream, bufferSize: 65536);
using var writer = new StreamWriter(outputStream, bufferSize: 65536);
// Disable buffer flush for performance improvement
writer.AutoFlush = false;
string? line;
while ((line = reader.ReadLine()) is not null)
{
writer.WriteLine(ProcessLine(line));
}
// Manual flush at the end
writer.Flush();
```
### 2.2 For Algorithm Problem Solving
```csharp
using System.Text;
// High-speed input
using var reader = new StreamReader(
Console.OpenStandardInput(),
Encoding.ASCII,
bufferSize: 65536);
// High-speed output
using var writer = new StreamWriter(
Console.OpenStandardOutput(),
Encoding.ASCII,
bufferSize: 65536);
var sb = new StringBuilder();
// Collect large output in StringBuilder and write at once
for (int i = 0; i < 100000; i++)
{
sb.AppendLine(i.ToString());
}
writer.Write(sb);
writer.Flush();
```
---
## 3. File I/O Optimization
### 3.1 Buffer Size Optimization
```csharp
// Use larger buffer than default (4KB)
const int bufferSize = 64 * 1024; // 64KB
using var fileStream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize: bufferSize);
```
### 3.2 Async File I/O
```csharp
// Open file with async option
using var fileStream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize: 4096,
options: FileOptions.Asynchronous);
var buffer = new byte[4096];
int bytesRead = await fileStream.ReadAsync(buffer);
```
### 3.3 SequentialScan Hint
```csharp
// Provide hint to OS for sequential reading
using var fileStream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize: 64 * 1024,
options: FileOptions.SequentialScan);
```
### 3.4 RandomAccess (.NET 6+)
```csharp
// Direct offset access without file position management
using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read);
var buffer = new byte[4096];
long offset = 1000;
int bytesRead = RandomAccess.Read(handle, buffer, offset);
// Async version
bytesRead = await RandomAccess.ReadAsync(handle, buffer, offset);
```
---
## 4. Large File Processing
### 4.1 Chunk-Based Reading
```csharp
public async IAsyncEnumerable<byte[]> ReadChunksAsync(
string path,
int chunkSize = 64 * 1024,
[EnumeratorCancellation] CancellationToken ct = default)
{
using var stream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize: chunkSize,
options: FileOptions.Asynchronous | FileOptions.SequentialScan);
var buffer = new byte[chunkSize];
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, ct)) > 0)
{
if (bytesRead == chunkSize)
{
yield return buffer;
buffer = new byte[chunkSize];
}
else
{
yield return buffer[..bytesRead];
}
}
}
```
### 4.2 Memory-Mapped Files
```csharp
using System.IO.MemoryMappedFiles;
// Map large file to memory
using var mmf = MemoryMappedFile.CreateFromFile(path, FileMode.Open);
using var accessor = mmf.CreateViewAccessor();
// Direct memory access
byte value = accessor.ReadByte(position);
accessor.Write(position, newValue);
```
---
## 5. Performance Comparison
| Method | Relative Performance | Use Case |
|--------|---------------------|----------|
| Console.ReadLine() | 1x (baseline) | General |
| StreamReader (default buffer) | 2x | Large data |
| StreamReader (64KB buffer) | 3-5x | Large data |
| MemoryMappedFile | 5-10x | Very large data |
---
## 6. Important Notes
### Buffer Size
- Too small increases system calls
- Too large wastes memory
- Recommended: 4KB ~ 64KB
### Encoding Specification
```csharp
// Read UTF-8 without BOM
using var reader = new StreamReader(
stream,
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
```
### Flush Timing
```csharp
// Improve performance with AutoFlush = false
writer.AutoFlush = false;
// Manual flush after important data
writer.Flush();
```
---
## 7. References
- [File and Stream I/O](https://learn.microsoft.com/en-us/dotnet/standard/io/)
- [Memory-Mapped Files](https://learn.microsoft.com/en-us/dotnet/standard/io/memory-mapped-files)
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.