File in use with .net method but not with powershell cmdlet

核能气质少年 提交于 2019-12-06 10:10:00

PetSerAl, as usual, has provided a terse comment that provides an effective solution and implies an explanation:

To prevent the "The process cannot access the file 'XYZ' because it is being used by another process." error, you must open the file with sharing mode FileShare.ReadWrite, so that other processes that want to write to the file aren't denied access.

This is what Get-Content (invariably) does behind the scenes, which explains why the problem doesn't surface when you use it.

By contrast, [System.IO.File]::OpenRead() defaults to sharing mode FileShare.Read, meaning that other processes can read from, but not write to the same file.

Therefore, use [System.IO.File]::Open() instead, which allows you to specify the sharing mode explicitly:

$fs = [IO.File]::Open($path, 
                  [IO.FileMode]::Open, 
                  [IO.FileAccess]::Read, 
                  [IO.FileShare]::ReadWrite)
# ...
$fs.Close()

Note that I've omitted the System. component from the type names above; this component is always optional in PowerShell.

If you could move to more later version of PowerShell (at least v3.0), then Get-Content -Tail is a good option. We use it widely and performance is good for our scenarios.

Official docs

Gets the specified number of lines from the end of a file or other item.
This parameter is introduced in Windows PowerShell 3.0.
You can use the "Tail" parameter name or its alias, "Last".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!