MeWrite Docs

System.IO.FileNotFoundException

ファイルまたはアセンブリが見つからない場合に発生するC#の例外

概要

System.IO.FileNotFoundExceptionは、指定されたパスにファイルが存在しない場合や、必要なDLL/アセンブリが見つからない場合に発生します。ファイルパスの問題だけでなく、依存関係の問題でも発生する点に注意が必要です。

エラーメッセージ

System.IO.FileNotFoundException: Could not find file 'C:\app\data\config.json'.
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified.

原因

  1. ファイルパスの誤り: パスのタイプミス、相対パスと絶対パスの混同
  2. 作業ディレクトリの違い: 開発環境と実行環境で作業ディレクトリが異なる
  3. DLLの不足: NuGetパッケージの復元漏れ、ビルド出力にDLLが含まれていない
  4. アセンブリバージョンの不一致: バインディングリダイレクトの設定漏れ
  5. ファイルのコピー設定漏れ: ビルド時にファイルが出力ディレクトリにコピーされていない

解決策

1. File.Existsで事前チェックする

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
string filePath = @"C:\app\data\config.json";

// NG: ファイルの存在を確認せずにアクセス
var content = File.ReadAllText(filePath);

// OK: 事前チェック
if (File.Exists(filePath))
{
    var content = File.ReadAllText(filePath);
    Console.WriteLine(content);
}
else
{
    Console.WriteLine($"ファイルが見つかりません: {filePath}");
}

// OK: try-catchで処理
try
{
    var content = await File.ReadAllTextAsync(filePath);
}
catch (FileNotFoundException ex)
{
    Console.WriteLine($"ファイルが見つかりません: {ex.FileName}");
}
catch (DirectoryNotFoundException)
{
    Console.WriteLine($"ディレクトリが見つかりません: {Path.GetDirectoryName(filePath)}");
}

2. 実行ディレクトリを基準にパスを構築する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// NG: 相対パス(作業ディレクトリ依存)
var path = "config.json";

// OK: 実行ファイルの場所を基準にする
var baseDir = AppContext.BaseDirectory;
var path = Path.Combine(baseDir, "config.json");
Console.WriteLine($"探索パス: {path}");

// ASP.NET Coreの場合
public class MyService
{
    private readonly IWebHostEnvironment _env;

    public MyService(IWebHostEnvironment env)
    {
        _env = env;
    }

    public string ReadConfig()
    {
        var path = Path.Combine(_env.ContentRootPath, "config.json");
        return File.ReadAllText(path);
    }
}

3. ビルドアクションとコピー設定を確認する

1
2
3
4
5
6
7
8
9
<!-- .csprojファイル: ファイルを出力ディレクトリにコピー -->
<ItemGroup>
    <None Update="config.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>

    <!-- 埋め込みリソースとして含める場合 -->
    <EmbeddedResource Include="data\template.json" />
</ItemGroup>
1
2
3
4
5
6
7
8
// 埋め込みリソースの読み取り
var assembly = Assembly.GetExecutingAssembly();
using var stream = assembly.GetManifestResourceStream("MyApp.data.template.json");
if (stream is not null)
{
    using var reader = new StreamReader(stream);
    var content = reader.ReadToEnd();
}

4. アセンブリバインディング問題を診断する

1
2
3
4
5
6
7
8
# dotnet CLIでの依存関係確認
dotnet publish -c Release
dotnet list package --include-transitive

# fuslogvw(アセンブリバインドログビューア)で詳細を確認
# Windows: レジストリでログを有効化
# HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion
# ForceLog = 1, LogPath = C:\fusionlog\
1
2
3
4
5
6
7
// 実行時にロードされたアセンブリを確認
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()
    .OrderBy(a => a.FullName))
{
    Console.WriteLine($"{asm.GetName().Name} v{asm.GetName().Version}");
    Console.WriteLine($"  場所: {asm.Location}");
}

5. NuGetパッケージの復元と依存関係の確認

1
2
3
4
5
6
7
8
9
# パッケージの復元
dotnet restore

# 依存関係ツリーの確認
dotnet list package --include-transitive

# ビルドしてDLLの存在を確認
dotnet build -c Release
ls bin/Release/net8.0/
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!-- バージョン競合の解決(.csproj) -->
<ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

<!-- .NET Frameworkの場合: app.configでバインディングリダイレクト -->
<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json"
                    publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-13.0.0.0"
                    newVersion="13.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>

関連エラー

C# の他のエラー

最終更新: 2026-02-03