读取数据的操作和随后的文件清理必须在一个会话中进行。和其他进程不应访问该文件。
$FileTwo = [System.io.File]::Open('C:\FiLeTwo.txt', "Open", "Read", "None")
$FileTwo2 = New-Object System.IO.StreamReader($FileTwo)
$text = $text + $FileTwo2.ReadToEnd()
$text = $text -replace '\ ' -replace 'g' -replace '\(' -replace '\)' -replace $re, "" #-replace '\n'
# Set-Content 'C:\FiLeTwo.txt' "" -Force
# IN that moment I need to clear the file.
# But I need cleare the file and, after, close the File ($FileTwo.Close())
$FileTwo.Close()
答案 0 :(得分:2)
您可以使用Clear-Content
删除文件的内容,但不能删除它。
示例:
Clear-Content c:\path\to\your\file.txt
您可以在此处了解更多信息: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/clear-content?view=powershell-6
答案 1 :(得分:1)
您甚至不需要使用那么多流:
$path = 'C:\FiLeTwo.txt'
$text = Get-Content $path -Raw
Clear-Content $path
$text = $text -Replace ...
如果要使用FileStream
,也可以使用SetLength
删除内容:
# open with "ReadWrite"
$fileTwo = [System.IO.File]::Open("C:\FiLeTwo.txt", "Open", "ReadWrite", "None")
try {
# ... read, replace etc ...
# clear the contents:
$fileTwo.SetLength(0);
}
finally {
# make sure to put this in a finally block!
$fileTwo.Dispose()
}
(请确保将它们的流正确放置在finally块中!)