2017-06-14 18 views
2

我使用PowerShell命令(get-item c:\temp\a.log).OpenRead()來測試文件發生了什麼。如何從鎖狀態釋放(get-item c: temp a.log).OpenRead()?

文件後打開閱讀,如果我發出(get-item c:\temp\a.log).OpenWrite(),它會返回下面的錯誤

Exception calling "OpenWrite" with "0" argument(s): "The process cannot access the file 
'C:\temp\a.log' because it is being used by another process." 
+ (get-item c:\temp\a.log).OpenWrite() 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : IOException 

我怎樣才能解除OpenRead()狀態?

回答

1

只是爲了說明,當你打開一個文件,.OpenRead(),然後用.OpenWrite()再次,它是由sharing(或缺乏)引起的,爲什麼你看到的這個行爲,而不是locking。共享規定在當前數據流仍處於打開狀態時允許從同一文件打開的其他數據流允許哪種訪問。

OpenReadOpenWrite是包裝FileStream constructor的便利方法; OpenRead創建一個允許讀共享的只讀流,並且OpenWrite創建一個只寫流,其中允許共享。您可能會注意到還有另一種稱爲Open的方法,其中有超載可讓您自己指定access(第二個參數)和共享(第三個參數)。我們可以翻譯OpenReadOpenWriteOpen,從而...

$read = (get-item c:\temp\a.log).OpenRead() 
# The following line throws an exception 
$write = (get-item c:\temp\a.log).OpenWrite() 

... ...變得

$read = (get-item c:\temp\a.log).Open('Open', 'Read', 'Read')   # Same as .OpenRead() 
# The following line throws an exception 
$write = (get-item c:\temp\a.log).Open('OpenOrCreate', 'Write', 'None') # Same as .OpenWrite() 
你寫

無論哪種方式,第三線將無法創建一個直寫只有流,因爲$read只會允許其他流讀取。防止這種衝突的一種方法是打開第二之前關閉第一流:

$read = (get-item c:\temp\a.log).Open('Open', 'Read', 'Read')   # Same as .OpenRead() 
try 
{ 
    # Use $read... 
} 
finally 
{ 
    $read.Close() 
} 

# The following line succeeds 
$write = (get-item c:\temp\a.log).Open('OpenOrCreate', 'Write', 'None') # Same as .OpenWrite() 
try 
{ 
    # Use $write... 
} 
finally 
{ 
    $write.Close() 
} 

如果你真的需要一個只讀和只寫流同時在同一個文件打開,你可以總是傳遞自己的價值觀,以Open允許這樣的:

$read = (get-item c:\temp\a.log).Open('Open', 'Read', 'ReadWrite') 
# The following line succeeds 
$write = (get-item c:\temp\a.log).Open('OpenOrCreate', 'Write', 'Read') 

注意,共享是雙向的:$read需要包括在其共享價值Write使$write可以Write訪問權限打開,並$write需要包括其共享價值爲Read因爲$read已經用Read訪問。

在任何情況下,當您完成使用任何情況下,在任何情況下都可以撥打Close()任何Stream

2

我找到了一種方法來解除鎖定狀態

我只是調用另一個命令:

$s = (get-item c:\temp\a.log).OpenRead() 

,然後用

$s.close() 

的文件不再被鎖定

+2

將其標記爲接受的答案 –

1

我發現以前的文章是可行的,因爲變量$ s就是我調用$ s =(get-ite m c:\ temp \ a.log).OpenRead()。

因此,$ s只是需要關閉的對象。

我嘗試以下測試以使其更清楚。

案例1:

$a = (get-item a.txt).OpenRead() #the a.txt is locked 
$a.Close() #a.txt is unlocked 

案例2:

$a = (get-item a.txt).OpenRead() #the a.txt is locked 
$b = (get-item a.txt).OpenRead() 
$a.Close() #a.txt is locked 
$b.close() #a.txt is unlocked 

情形3:

$a = (get-item a.txt).OpenRead() #the a.txt is locked 
$a = "bbb" #the a.txt is locked for a while, finally it will unlock 

對於情形3,似乎該系統將處理懸掛物體,然後解除鎖定狀態。