指定するファイルに対してコメントを記録するコンソールアプリです。
一つの外部コマンドで、コメントの追加・変更・削除を行います。
コメントの記憶はDBではなくシンプルなテキストファイルです。ただ、ファイル名にハッシュ値(MD5)を使うことで、同じディレクトリで重複しないファイル名になるように工夫しています。
ソースコード
ファイル名:comment.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
</PropertyGroup>
</Project>
ファイル名:Program.cs
using System.Security.Cryptography;
using System.Text;
if (args.Length < 1) return;
var target = args[0];
// 保存先: ドキュメント\comment
var commentDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"comment");
Directory.CreateDirectory(commentDir);
// パス正規化(大小無視・末尾区切り削除)
var canonical = Path.GetFullPath(target)
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.ToLowerInvariant();
// ハッシュ名(md5)
var hash = Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(canonical))).ToLowerInvariant();
var commentFile = Path.Combine(commentDir, $"{hash}.txt");
// 元ファイルが存在しない
if (!File.Exists(canonical))
{
if (File.Exists(commentFile))
File.Delete(commentFile);
return;
}
// コメントの取得(第2引数 or 標準入力)
string? argComment = args.Length >= 2 ? args[1] : null;
string? comment = argComment ?? (Console.IsInputRedirected ? Console.In.ReadToEnd() : null);
// 第2引数なし=閲覧
if (comment is null)
{
if (File.Exists(commentFile))
Console.WriteLine(File.ReadAllText(commentFile));
return;
}
// 空文字=削除
if (string.IsNullOrWhiteSpace(comment))
{
if (File.Exists(commentFile)) File.Delete(commentFile);
return;
}
// それ以外=保存
File.WriteAllText(commentFile, comment);
ビルド
dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true /p:IncludeAllContentForSelfExtract=true /p:SelfContained=true --output "exeの出力先のディレクトリ"
実行
# コメントの追加・更新
comment.exe 対象ファイルのパス.txt "コメント内容"
# コメントの取得→標準出力
comment.exe 対象ファイルのパス.txt
# コメントの削除
comment.exe 対象ファイルのパス.txt " "
ls(Get-ChildItem)と連動させた例
ls . | % { [PSCustomObject]@{'FullName'=$_.FullName;'Comment'=(comment $_.FullName)} }
#FullName Comment
#-------- -------
#C:\csharp\console\comment\.vscode
#C:\csharp\console\comment\bin
#C:\csharp\console\comment\obj
#C:\csharp\console\comment\comment.csproj C#プロジェクトファイル
#C:\csharp\console\comment\Program.cs C#ソースコード
#C:\csharp\console\comment\sample.txt テスト
追記:
ディレクトリが対象になっていなかった。
コメント
まあまあ面白い 最近はAIのせいで誰でもCode出すようになっちまいましたね。