5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[C#]フォルダが削除できないときの雑な対策

Last updated at Posted at 2022-02-27

発生条件

一瞬の間にフォルダ作成とフォルダ削除を行おうとすると下記例外が発生した。

System.IO.IOException : The process cannot access the file
'ccc0.txt' because it is being used by another process.

解決方法

非同期でかつ遅延させて実行するとうまく行った。

Task.Run(async () =>
{
    await Task.Delay(500); // 500ms遅延
    Directory.Delete("aaa", true); // フォルダ削除
});

※遅延の秒数は適当。短いと失敗しやすい傾向にあったので、500[ms]に落ち着いた。コメント頂いてるように、真剣にやるときは遅延とリトライを繰り返す機構があるといい。

背景

xUnitでファイルをいじるロジックのテストを書く場面があり、テスト用ファイルの生成/削除をコンストラクタとDispose()で行おうと思い立った。
とりあえずその部分の動作だけ確かめようとしたところ、冒頭の例外発生。

他のプロセスに使われているというメッセージだがそんなわけがない。多分、ファイル生成してすぐだから自分のプロセスのことなんだろう。

テストケース内にいくらか時間がかかる処理が書かれれば起きなくなるトラブルなんだろうけど、エラーメッセージと直接原因が噛み合わないケースなので情報共有。

5
3
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?