2011-04-02 43 views
12

我不確定通常是什麼人通過「鎖定」一個文件的意思,但我想要的是做一個文件,當我試圖打開它會產生一個「指定的文件正在使用」錯誤信息的文件與其他應用程序。如何用C#鎖定文件?

我想這樣做來測試我的應用程序,看看它在我嘗試打開處於此狀態的文件時的行爲。我嘗試這樣做:

FileStream fs = null; 

private void lockToolStripMenuItem_Click(object sender, EventArgs e) 
{ 
    fs = new FileStream(@"C:\Users\Juan Luis\Desktop\corte.txt", FileMode.Open); 
} 

private void unlockToolStripMenuItem_Click(object sender, EventArgs e) 
{ 
    fs.Close(); 
} 

但顯然它並沒有做什麼,我預料之中,因爲我能夠打開該文件,用記事本,而這是「鎖定」。那麼如何鎖定一個文件,使其不能用另一個應用程序打開以用於我的測試目的呢?

回答

22

您需要的None一個FileShare枚舉值傳遞給上FileStream constructor overloads打開:

fs = new FileStream(@"C:\Users\Juan Luis\Desktop\corte.txt", FileMode.Open, 
    FileAccess.ReadWrite, FileShare.None); 
+14

希望我有時可以同時接受的答案,因爲它們幾乎完全一樣。希望你不介意我因爲他的低分而接受其他人:) – Juan 2011-04-02 09:23:33

1

雖然FileShare.None無疑是一個快速簡便的解決方案鎖定整個文件,你可以鎖定文件的一部分使用FileStream.Lock()

public virtual void Lock(
    long position, 
    long length 
) 

Parameters 

position 
    Type: System.Int64 
    The beginning of the range to lock. The value of this parameter must be equal to or greater than zero (0). 

length 
    Type: System.Int64 
    The range to be locked. 

,相反,你可以使用以下方法來解鎖文件:FileStream.Unlock()

public virtual void Unlock(
    long position, 
    long length 
) 

Parameters 

position 
    Type: System.Int64 
    The beginning of the range to unlock. 

length 
    Type: System.Int64 
    The range to be unlocked.