Token导航 LogoToken导航

Agent Skill · 开发

dotnet-file-io(点网文件 io)

dotnet-file-io 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

dotnet-file-io 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 17,811。

总安装 376周安装 16GitHub Stars 15下载 132核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:dotnet-file-io(点网文件 io)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/dotnet-file-io
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-file-io
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-file-io

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

该技能提供 .NET 文件 I/O 的安全高效模式,支持大文件和 IPC 场景。适用于 FileStream、MemoryMappedFile 和 FileSystemWatcher 使用场景。核心能力包括异步构造、RandomAccess 线程安全和路径安全处理。使用时应注意缓冲区大小和临时文件安全创建。

安装前需确认项目目标平台支持所需文件系统特性。

来源仓库内路径:skills/dotnet-file-io

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-file-io;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

dotnet-file-io 怎么安装?

在终端执行 npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-file-io。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

dotnet-file-io 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

dotnet-file-io 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

dotnet-file-io 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

dotnet-file-io 用的人多吗?

公开数据是累计安装 376 次,近一周安装 16 次,下载 132 次,GitHub 15 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

dotnet-file-io 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
dotnet-file-io

点网文件 io · 本页

37615需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

dotnet-file-io

File I/O patterns for.NET applications. Covers FileStream construction with async flags, RandomAccess API for thread-safe offset-based I/O, File convenience methods, FileSystemWatcher event handling and debouncing, MemoryMappedFile for large files and IPC, path handling security (Combine vs Join), secure temp file creation, cross-platform considerations, IOException hierarchy, and buffer sizing guidance.

Out of scope: PipeReader/PipeWriter and network I/O -- see [skill:dotnet-io-pipelines]. Async/await fundamentals -- see [skill:dotnet-csharp-async-patterns]. Span/Memory/ArrayPool deep patterns -- see [skill:dotnet-performance-patterns]. JSON and Protobuf serialization -- see [skill:dotnet-serialization]. BackgroundService lifecycle -- see [skill:dotnet-background-services]. Channel producer/consumer -- see [skill:dotnet-channels]. GC implications of pinned/memory-mapped backing arrays -- see [skill:dotnet-gc-memory]. File upload validation (IFormFile) -- see [skill:dotnet-input-validation].

For testable file system access, consider System.IO.Abstractions -- see [skill:dotnet-testing-strategy] for test isolation patterns.

Cross-references: [skill:dotnet-io-pipelines] for PipeReader/PipeWriter network I/O, [skill:dotnet-gc-memory] for POH and memory-mapped backing array GC implications, [skill:dotnet-performance-patterns] for Span/Memory basics and ArrayPool usage, [skill:dotnet-csharp-async-patterns] for async/await patterns used with file streams.


FileStream

Async Flag Requirement

FileStream async methods (ReadAsync, WriteAsync) silently block the calling thread unless the stream is opened with the async flag. This is the most common file I/O mistake in.NET code.

// CORRECT: async-capable FileStream
await using var fs = new FileStream(
    path,
    FileMode.Open,
    FileAccess.Read,
    FileShare.Read,
    bufferSize: 4096,
    useAsync: true);  // Required for true async I/O

byte[] buffer = new byte[4096];
int bytesRead = await fs.ReadAsync(buffer, cancellationToken);
// ALSO CORRECT: FileOptions overload
await using var fs = new FileStream(
    path,
    FileMode.Create,
    FileAccess.Write,
    FileShare.None,
    bufferSize: 4096,
    FileOptions.Asynchronous | FileOptions.SequentialScan);

Without useAsync: true or FileOptions.Asynchronous, the runtime emulates async by dispatching synchronous I/O to the thread pool -- wasting a thread and adding overhead.

FileStreamOptions (.NET 6+)

await using var fs = new FileStream(path, new FileStreamOptions
{
    Mode = FileMode.Open,
    Access = FileAccess.Read,
    Share = FileShare.Read,
    Options = FileOptions.Asynchronous | FileOptions.SequentialScan,
    BufferSize = 4096,
    PreallocationSize = 1_048_576  // Hint for write: reduces fragmentation
});

PreallocationSize reserves disk space upfront when creating or overwriting files, reducing filesystem fragmentation on writes.


RandomAccess API (.NET 6+)

RandomAccess provides static, offset-based, thread-safe file I/O. Unlike FileStream, it has no internal position state, so multiple threads can read/write different offsets concurrently without synchronization.

using var handle = File.OpenHandle(
    path,
    FileMode.Open,
    FileAccess.Read,
    FileShare.Read,
    FileOptions.Asynchronous);

// Thread-safe: offset is explicit, no shared position
byte[] buffer = new byte[4096];
int bytesRead = await RandomAccess.ReadAsync(
    handle, buffer, fileOffset: 0, cancellationToken);

// Read from a different offset concurrently -- no locking needed
byte[] buffer2 = new byte[4096];
int bytesRead2 = await RandomAccess.ReadAsync(
    handle, buffer2, fileOffset: 8192, cancellationToken);

Scatter/Gather I/O

// Read into multiple buffers in a single syscall
IReadOnlyList<Memory<byte>> buffers = new[]
{
    new byte[4096].AsMemory(),
    new byte[4096].AsMemory()
};
long totalRead = await RandomAccess.ReadAsync(
    handle, buffers, fileOffset: 0, cancellationToken);

When to Use RandomAccess vs FileStream

ScenarioUse
Concurrent reads from different offsetsRandomAccess
Sequential streaming reads/writesFileStream
Index files, database pages, memory-mapped alternativesRandomAccess
Integration with Stream-based APIsFileStream

File Convenience Methods

For small files where streaming is unnecessary, the File static methods are simpler and correct.

// Read entire file as string (small files only)
string content = await File.ReadAllTextAsync(path, cancellationToken);

// Read all lines
string[] lines = await File.ReadAllLinesAsync(path, cancellationToken);

// Stream lines without loading entire file (.NET 8+)
await foreach (string line in File.ReadLinesAsync(path, cancellationToken))
{
    ProcessLine(line);
}

// Write text atomically (write-then-rename pattern not built-in)
await File.WriteAllTextAsync(path, content, cancellationToken);

// Read all bytes
byte[] data = await File.ReadAllBytesAsync(path, cancellationToken);

When Convenience Methods Are Appropriate

File sizeApproach
< 1 MBFile.ReadAllTextAsync / File.ReadAllBytesAsync
1--100 MBFile.ReadLinesAsync or FileStream with buffered reading
> 100 MBFileStream or RandomAccess with explicit buffer management

FileSystemWatcher

Basic Setup

using var watcher = new FileSystemWatcher(directoryPath)
{
    Filter = "*.json",
    NotifyFilter = NotifyFilters.FileName
                 | NotifyFilters.LastWrite
                 | NotifyFilters.Size,
    IncludeSubdirectories = true,
    EnableRaisingEvents = true
};

watcher.Changed += OnChanged;
watcher.Created += OnCreated;
watcher.Deleted += OnDeleted;
watcher.Renamed += OnRenamed;
watcher.Error += OnError;

Debouncing Duplicate Events

FileSystemWatcher fires duplicate events for a single logical change (editors write temp file, rename, delete old). Debounce with a timer.

public sealed class DebouncedFileWatcher : IDisposable
{
    private readonly FileSystemWatcher _watcher;
    private readonly Channel<string> _channel;
    private readonly CancellationTokenSource _cts = new();

    public DebouncedFileWatcher(string path, string filter)
    {
        _channel = Channel.CreateBounded<string>(
            new BoundedChannelOptions(100)
            {
                FullMode = BoundedChannelFullMode.DropOldest
            });

        _watcher = new FileSystemWatcher(path, filter)
        {
            EnableRaisingEvents = true
        };
        _watcher.Changed += (_, e) =>
            _channel.Writer.TryWrite(e.FullPath);
    }

    // requires: using System.Runtime.CompilerServices;
    public async IAsyncEnumerable<string> WatchAsync(
        TimeSpan debounce,
        [EnumeratorCancellation] CancellationToken ct = default)
    {
        using var linked = CancellationTokenSource
            .CreateLinkedTokenSource(ct, _cts.Token);
        var seen = new Dictionary<string, DateTime>();

        await foreach (var path in
            _channel.Reader.ReadAllAsync(linked.Token))
        {
            var now = DateTime.UtcNow;
            if (seen.TryGetValue(path, out var last)
                && now - last < debounce)
                continue;

            seen[path] = now;
            yield return path;
        }
    }

    public void Dispose()
    {
        _cts.Cancel();
        _watcher.Dispose();
        _cts.Dispose();
    }
}

Buffer Overflow

The internal buffer defaults to 8 KB. When many changes occur rapidly, the buffer overflows and events are lost. Increase with InternalBufferSize (max 64 KB on Windows) and handle the Error event.

watcher.InternalBufferSize = 65_536;  // 64 KB
watcher.Error += (_, e) =>
{
    if (e.GetException() is InternalBufferOverflowException)
    {
        logger.LogWarning("FileSystemWatcher buffer overflow -- events lost");
        // Trigger full directory rescan
    }
};

Platform Differences

PlatformBackendNotable behavior
WindowsReadDirectoryChangesWMost reliable; supports InternalBufferSize up to 64 KB
LinuxinotifyWatch limit per user (/proc/sys/fs/inotify/max_user_watches); recursive watches add one inotify watch per subdirectory
macOSFSEvents (kqueue fallback)Coarser event granularity; may batch events with slight delay

MemoryMappedFile

Persisted (Large File Access)

Map a file into virtual memory for random access without explicit read/write calls. Efficient for large files that do not fit in memory -- the OS pages data in and out as needed.

using var mmf = MemoryMappedFile.CreateFromFile(
    path,
    FileMode.Open,
    mapName: null,
    capacity: 0,  // Use file's actual size
    MemoryMappedFileAccess.Read);

using var accessor = mmf.CreateViewAccessor(
    offset: 0,
    size: 0,  // Map entire file
    MemoryMappedFileAccess.Read);

// Read a struct at a specific offset
accessor.Read<MyHeader>(position: 0, out var header);

// Or use a view stream for sequential access
using var stream = mmf.CreateViewStream(
    offset: 0,
    size: 4096,
    MemoryMappedFileAccess.Read);

Non-Persisted (IPC Shared Memory)

// Process A: create shared memory region
using var mmf = MemoryMappedFile.CreateNew(
    "SharedRegion",
    capacity: 1_048_576,  // 1 MB
    MemoryMappedFileAccess.ReadWrite);

using var accessor = mmf.CreateViewAccessor();
accessor.Write(0, 42);

// Process B: open existing shared memory region
using var mmf2 = MemoryMappedFile.OpenExisting(
    "SharedRegion",
    MemoryMappedFileRights.Read);

using var accessor2 = mmf2.CreateViewAccessor(
    0, 0, MemoryMappedFileAccess.Read);
int value = accessor2.ReadInt32(0);  // 42

For GC implications of memory-mapped backing arrays and POH usage, see [skill:dotnet-gc-memory].


Path Handling

Path.Combine vs Path.Join Security

Path.Combine silently discards the first argument when the second argument is a rooted path. This enables path traversal attacks when user input is passed as the second argument.

// DANGEROUS: Path.Combine drops basePath when userInput is rooted
string basePath = "/app/uploads";
string userInput = "/etc/passwd";
string result = Path.Combine(basePath, userInput);
// result = "/etc/passwd"  -- basePath is silently ignored

// SAFER: Path.Join does not discard on rooted paths (.NET Core 2.1+)
string result2 = Path.Join(basePath, userInput);
// result2 = "/app/uploads//etc/passwd"  -- preserves basePath

Path Traversal Prevention

public static string SafeResolvePath(string basePath, string userPath)
{
    // Resolve to absolute, resolving ../ and symlinks
    string fullBase = Path.GetFullPath(basePath);
    string fullPath = Path.GetFullPath(
        Path.Join(fullBase, userPath));

    // OrdinalIgnoreCase: safe cross-platform default.
    // On Linux-only deployments, Ordinal is more precise.
    if (!fullPath.StartsWith(fullBase + Path.DirectorySeparatorChar,
            StringComparison.OrdinalIgnoreCase)
        && !fullPath.Equals(fullBase, StringComparison.OrdinalIgnoreCase))
    {
        throw new UnauthorizedAccessException(
            "Path traversal detected");
    }

    return fullPath;
}

Cross-Platform Path Separators

Use Path.DirectorySeparatorChar (platform-specific) and Path.AltDirectorySeparatorChar instead of hardcoded / or \\. Path.Join and Path.Combine handle separator normalization automatically.


Secure Temp Files

Path.GetTempFileName() creates a zero-byte file with a predictable name pattern and throws when the temp directory contains 65,535 .tmp files. Use Path.GetRandomFileName() instead.

// INSECURE: predictable name, may throw IOException
// string tempFile = Path.GetTempFileName();

// SECURE: cryptographically random name, explicit creation
string tempPath = Path.Join(
    Path.GetTempPath(),
    Path.GetRandomFileName());

// CreateNew ensures atomic creation -- fails if file exists
await using var fs = new FileStream(
    tempPath,
    FileMode.CreateNew,
    FileAccess.Write,
    FileShare.None,
    bufferSize: 4096,
    FileOptions.Asynchronous | FileOptions.DeleteOnClose);

await fs.WriteAsync(data, cancellationToken);

FileOptions.DeleteOnClose ensures the temp file is removed when the stream is closed. On Windows, the OS guarantees deletion when the last handle closes. On Linux/macOS, deletion happens during Dispose and may not occur if the process is killed abruptly (SIGKILL).


Cross-Platform Considerations

Case Sensitivity

PlatformDefault filesystemCase behavior
WindowsNTFSCase-preserving, case-insensitive
macOSAPFSCase-preserving, case-insensitive (default)
Linuxext4/xfsCase-sensitive

Use StringComparison.OrdinalIgnoreCase for path comparisons that must work cross-platform. Do not assume case sensitivity behavior -- check at runtime if needed.

UnixFileMode (.NET 7+)

// Set POSIX permissions on file creation (Linux/macOS only)
await using var fs = new FileStream(path, new FileStreamOptions
{
    Mode = FileMode.Create,
    Access = FileAccess.Write,
    UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite
    // 0600 -- owner read/write only
});

On Windows, UnixCreateMode is silently ignored. Do not use it as a security control on Windows -- use ACLs or Windows security APIs instead.

File Locking

PlatformLock typeBehavior
WindowsMandatoryOther processes cannot read/write locked regions
LinuxAdvisory (flock/fcntl)Locks are cooperative -- processes can ignore them
macOSAdvisory (flock)Same as Linux -- cooperative

FileShare flags control sharing on Windows. On Linux/macOS, use FileStream.Lock for advisory locking but be aware that non-cooperating processes can bypass it.


Error Handling

IOException Hierarchy

IOException
  +-- FileNotFoundException
  +-- DirectoryNotFoundException
  +-- PathTooLongException
  +-- DriveNotFoundException
  +-- EndOfStreamException
  +-- FileLoadException

HResult Codes for Specific Conditions

try
{
    await using var fs = new FileStream(path,
        FileMode.Open, FileAccess.Read);
    // ...
}
catch (IOException ex) when (ex.HResult == unchecked((int)0x80070070))
{
    // ERROR_DISK_FULL (Windows) -- disk full
    logger.LogError("Disk full: {Path}", path);
}
catch (IOException ex) when (ex.HResult == unchecked((int)0x80070020))
{
    // ERROR_SHARING_VIOLATION -- file locked by another process
    logger.LogWarning("File locked: {Path}", path);
}
catch (UnauthorizedAccessException ex)
{
    // Permission denied (not an IOException subclass)
    logger.LogError("Access denied: {Path}", path);
}

Disk-Full Flush Behavior

Write operations may succeed but buffer data in memory. A disk-full condition can surface at Flush or Dispose time rather than at the Write call. Always check for exceptions on flush.

await using var fs = new FileStream(path,
    FileMode.Create, FileAccess.Write,
    FileShare.None, 4096, FileOptions.Asynchronous);

await fs.WriteAsync(data, cancellationToken);

// IOException (disk full) may throw here, not at WriteAsync
await fs.FlushAsync(cancellationToken);

Buffer Sizing

Guidance based on dotnet/runtime benchmarks and internal FileStream implementation:

File operationRecommended bufferRationale
Small file sequential read (< 1 MB)4 KB (default)Matches OS page size; FileStream default
Large file sequential read (> 1 MB)64--128 KBAmortizes syscall overhead; diminishing returns above 128 KB
Network-attached storage (NFS/SMB)64 KBLarger buffers amortize network round-trips
SSD random access4 KBMatches SSD page size; larger buffers waste read-ahead
FileStream sequential scan4 KB + FileOptions.SequentialScanOS read-ahead handles prefetching

FileOptions.SequentialScan hints the OS to prefetch data ahead of the read position. It is beneficial for sequential reads and can degrade performance for random access patterns.


Agent Gotchas

  1. Do not use FileStream async methods without useAsync: true -- without the async flag, ReadAsync/WriteAsync dispatch synchronous I/O to the thread pool, blocking a thread and adding overhead. Always pass useAsync: true or FileOptions.Asynchronous.
  2. Do not use Path.Combine with untrusted input -- Path.Combine silently discards the base path when the second argument is rooted, enabling path traversal. Use Path.Join (.NET Core 2.1+) and validate the resolved path is under the intended base directory.
  3. Do not use Path.GetTempFileName() -- it creates predictable filenames and throws at 65,535 files. Use Path.GetRandomFileName() with FileMode.CreateNew for secure, atomic temp file creation.
  4. Do not ignore FileSystemWatcher duplicate events -- editors and tools trigger multiple events for a single logical change. Implement debouncing with a timer or Channel throttle.
  5. Do not rely on FileSystemWatcher alone for reliable change detection -- buffer overflows lose events silently. Handle the Error event and implement periodic rescan as a fallback.
  6. Do not assume file locking is mandatory on Linux/macOS -- FileStream.Lock and FileShare flags use advisory locking on Unix, which non-cooperating processes can bypass. Design protocols accordingly.
  7. Do not catch only IOException and ignore UnauthorizedAccessException -- permission errors throw UnauthorizedAccessException, which does not inherit from IOException. Handle both in file access error handling.
  8. Do not assume WriteAsync reports disk-full errors immediately -- data may be buffered. Disk-full IOException can surface at FlushAsync or Dispose. Always handle exceptions on flush.

References

平台分布

Codex

39.49%
按下载量换算52

Claude

31.57%
按下载量换算42

Cursor

17.08%
按下载量换算23

Gemini CLI

8.62%
按下载量换算11

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills