Lock Method

FileStream.Lock Method

Prevents other processes from changing the FileStream.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)

Public Overridable Sub Lock ( _
	position As Long, _
	length As Long _
Dim instance As FileStream 
Dim position As Long 
Dim length As Long

instance.Lock(position, length)


Type: System.Int64

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

Type: System.Int64

The range to be locked.


position or length is negative.


The file is closed.


The process cannot access the file because another process has locked a portion of the file.

Locking a range of a file stream gives the threads of the locking process exclusive access to that range of the file stream.

For a list of common I/O tasks, see Common I/O Tasks.

The following code example demonstrates how to lock part of a file so another process cannot access that part of the file even though it has read/write access to the file. Run the program simultaneously in different command windows and investigate using the different console input options.

Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Text

Public Class FStreamLock

    Shared Sub Main()

        Dim uniEncoding As New UnicodeEncoding()
        Dim lastRecordText As String = _
            "The last processed record number was: " 
        Dim textLength As Integer = _
        Dim recordNumber As Integer = 13
        Dim byteCount As Integer = _
        Dim tempString As String  

        Dim aFileStream As New FileStream( _
            "Test#@@#.dat", FileMode.OpenOrCreate, _
            FileAccess.ReadWrite, FileShare.ReadWrite)

            ' Write the original file data. 
            If aFileStream.Length = 0 Then
                tempString = _
                    lastRecordText + recordNumber.ToString()
                aFileStream.Write(uniEncoding.GetBytes(tempString), _
                    0, uniEncoding.GetByteCount(tempString))
            End If 

            ' Allow the user to choose the operation. 
            Dim consoleInput As Char = "R"C
            Dim readText(CInt(aFileStream.Length)) As Byte
            While consoleInput <> "X"C

                Console.Write(vbcrLf & _
                    "Enter 'R' to read, 'W' to write, 'L' to " & _ 
                    "lock, 'U' to unlock, anything else to exit: ")

                tempString = Console.ReadLine()
                If tempString.Length = 0 Then 
                    Exit While 
                End If
                consoleInput = Char.ToUpper(tempString.Chars(0))
                Select consoleInput

                    ' Read data from the file and  
                    ' write it to the console. 
                    Case "R"C
                            aFileStream.Seek(0, SeekOrigin.Begin)
                            aFileStream.Read( _
                                readText, 0, CInt(aFileStream.Length))
                            tempString = New String( _
                                uniEncoding.GetChars( _
                                readText, 0, readText.Length))
                            recordNumber = Integer.Parse( _
                                tempString.Substring( _
                                tempString.IndexOf(":"C) + 2))

                        ' Catch the IOException generated if the  
                        ' specified part of the file is locked. 
                        Catch ex As IOException
                            Console.WriteLine("{0}: The read " & _
                                "operation could not be performed " & _
                                "because the specified part of the" & _
                                " file is locked.", _
                        End Try 
                        Exit Select 

                    ' Update the file. 
                    Case "W"C
                            aFileStream.Seek(textLength, _
                            aFileStream.Read( _
                                readText, textLength - 1, byteCount)
                            tempString = New String( _
                                uniEncoding.GetChars( _
                                readText, textLength - 1, byteCount))
                            recordNumber = _
                                Integer.Parse(tempString) + 1
                            aFileStream.Seek( _
                                textLength, SeekOrigin.Begin)
                            aFileStream.Write(uniEncoding.GetBytes( _
                                recordNumber.ToString()), 0, byteCount)
                            Console.WriteLine( _
                                "Record has been updated.")

                        ' Catch the IOException generated if the  
                        ' specified part of the file is locked. 
                        Catch ex As IOException
                            Console.WriteLine( _
                                "{0}: The write operation could " & _
                                "not be performed because the " & _
                                "specified part of the file is " & _
                                "locked.", ex.GetType().Name)
                        End Try 
                        Exit Select 

                    ' Lock the specified part of the file. 
                    Case "L"C
                            aFileStream.Lock(textLength - 1, byteCount)
                            Console.WriteLine("The specified part " & _
                                "of file has been locked.")
                        Catch ex As IOException
                            Console.WriteLine( _
                                "{0}: The specified part of file " & _
                                "is already locked.", _
                        End Try 
                        Exit Select 

                    ' Unlock the specified part of the file. 
                    Case "U"C
                            aFileStream.Unlock( _
                                textLength - 1, byteCount)
                            Console.WriteLine("The specified part " & _
                                "of file has been unlocked.")
                        Catch ex As IOException
                            Console.WriteLine( _
                                "{0}: The specified part of file " & _
                                "is not locked by the current " & _
                                "process.", ex.GetType().Name)
                        End Try 
                        Exit Select 

                    ' Exit the program. 
                    Case Else
                        consoleInput = "X"C
                        Exit While 
                End Select 
            End While 

        End Try 

    End Sub 
End Class

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

Community Additions

© 2016 Microsoft