关闭.NET打开的文件句柄 [英] Close a file handle opened by .NET
问题描述
我正在研究一个脚本,用于根据EXIF数据重命名文件.
I'm working on a script to rename files based on EXIF data.
param([string]$path)
# http://blogs.technet.com/b/jamesone/archive/2007/07/13/exploring-photographic-exif-data-using-powershell-of-course.aspx
[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll") | out-null
function MakeString {
$s=""
for ($i=0 ; $i -le $args[0].value.length; $i ++) {
$s = $s + [char]$args[0].value[$i]
}
return $s
}
$files = Get-ChildItem -Path $path
foreach ($file in $files) {
if ($file.Extension -ne ".jpg") { continue }
if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
$exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
$captureDate = MakeString $exif.GetPropertyItem(36867)
$captureDate = ($captureDate -replace ":", '-').Substring(0,19)
$newFilename = $captureDate + " " + $file.Name.Trim()
$file.Name + " -> " + $newFilename
$file |Rename-Item -NewName $newFilename
}
从EXIF读取日期没问题,但是当我尝试重命名文件时,出现以下错误消息:
Reading the date from EXIF is no problem, but when I try to rename the file I get this error message:
Rename-Item : The process cannot access the file because it is being used by another process.
At D:\Norwegen\RenamePhotos.ps1:25 char:12
+ $file |Rename-Item -NewName $newFilename
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (D:\Norwegen\P1270465 (1920x1433).jpg:String) [Rename-Item], IOException
+ FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
当我监视ProcMon中的目录时,我可以看到文件已关闭很晚:
When I monitor the directory in ProcMon I can see that the files are closed rather late:
(请查看突出显示的行,它来自当前正在处理的文件条目中间的一个较早的文件)
(look at the highlighted line, it's from an earlier file in the middle of the entries from the file currently being processed)
那么,如何关闭文件(可能仍会从EXIF读取中打开文件)以便重命名?
So, how can I close the file (which is probably still open from the EXIF read) so I can rename it?
我已经尝试关闭打开的文件:
What I already tried to close the open file:
Remove-Variable exif
$file.Close()
推荐答案
由于仅从文件中读取内容,因此调用Dispose()
应该可以解决问题.例
Since you only read from the the file, then a call to Dispose()
should do the trick. Ex.
foreach ($file in $files) {
if ($file.Extension -ne ".jpg") { continue }
if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
$exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
$captureDate = MakeString $exif.GetPropertyItem(36867)
#Disposing object as soon as possible
$exif.Dispose()
$captureDate = ($captureDate -replace ":", '-').Substring(0,19)
$newFilename = $captureDate + " " + $file.Name.Trim()
$file.Name + " -> " + $newFilename
$file |Rename-Item -NewName $newFilename
}
这篇关于关闭.NET打开的文件句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!