LoginSignup
3
4

More than 5 years have passed since last update.

ロックしないでファイル読み込み

Last updated at Posted at 2018-11-23

少し特殊ですが、ファイルをロックしないで読み込みしたくなりました。PowerShellで実装してみましたので、メモしておきます。

実装方法

ファイルをロックせずに、ファイル内容を標準出力します。ポイントは、ファイルオープン時に指定するFileShareのReadWrite、Deleteです。

no_locked_read.ps1
$inpath = 'D:\tmp\dummy.txt'
$sr = [System.IO.StreamReader]::new(
    [System.IO.FileStream]::new(
        $inpath,
        [System.IO.FileMode]::Open,
        [System.IO.FileAccess]::Read,
        # 他プログラムの読み書き、削除をロックしない
        [System.IO.FileShare]::ReadWrite + [System.IO.FileShare]::Delete))
echo $sr.ReadToEnd()
$sr.Close()

ファイルオープン部分は、次のように書くこともできますね。

$fs = [System.IO.File]::Open(
    $inpath,
    [System.IO.FileMode]::Open,
    [System.IO.FileAccess]::Read,
    [System.IO.FileShare]::ReadWrite + [System.IO.FileShare]::Delete)
$sr = [System.IO.StreamReader]::new($fs)

テキスト読み込み部分は、次のようにして、1行ごとに処理することもできますね。

while (($line = $sr.ReadLine()) -ne $null) {
    echo $line
}

ワンライナー

Windowsのコマンドプロンプトから、ワンライナーで実行する場合は、次のように書けました。

powershell -Command "$sr = [System.IO.StreamReader]::new([System.IO.FileStream]::new('D:\tmp\dummy.txt', [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite + [System.IO.FileShare]::Delete)); echo $sr.ReadToEnd(); $sr.Close()"

動作確認方法

上述のファイル読み込み中に、ロックがかかっていないことを動作確認するときは、読み込み処理の途中で、Start-Sleep 10(10秒のスリープ)などを入れると便利です。当プログラムを実行して、スリープ中に、他のプログラムから読み書き、削除ができることを確認できるはずです。なお、他のプログラムがファイル削除した場合、削除処理成功しますが、ファイルはまだ残っていて、当プログラムがファイルクローズ後に、ファイルが削除されました。

動作確認環境

  • Windows10
  • Powershell 5.1

参考

3
4
0

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
3
4