Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

FileStream.Lock Method

Prevents other processes from changing the FileStream.

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

'Declaration
Public Overridable Sub Lock ( _
	position As Long, _
	length As Long _
)
'Usage
Dim instance As FileStream 
Dim position As Long 
Dim length As Long

instance.Lock(position, 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.

ExceptionCondition
ArgumentOutOfRangeException

position or length is negative.

ObjectDisposedException

The file is closed.

IOException

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 = _
            uniEncoding.GetByteCount(lastRecordText)
        Dim recordNumber As Integer = 13
        Dim byteCount As Integer = _
            uniEncoding.GetByteCount(recordNumber.ToString())
        Dim tempString As String  

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

        Try 
            ' 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
                        Try
                            aFileStream.Seek(0, SeekOrigin.Begin)
                            aFileStream.Read( _
                                readText, 0, CInt(aFileStream.Length))
                            tempString = New String( _
                                uniEncoding.GetChars( _
                                readText, 0, readText.Length))
                            Console.WriteLine(tempString)
                            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.", _
                                ex.GetType().Name)
                        End Try 
                        Exit Select 

                    ' Update the file. 
                    Case "W"C
                        Try
                            aFileStream.Seek(textLength, _
                                SeekOrigin.Begin)
                            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)
                            aFileStream.Flush()
                            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
                        Try
                            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.", _
                                ex.GetType().Name)
                        End Try 
                        Exit Select 

                    ' Unlock the specified part of the file. 
                    Case "U"C
                        Try
                            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 

        Finally
            aFileStream.Close()    
        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

ADD
Show:
© 2015 Microsoft