FileStream::Lock Method

Prevents other processes from reading from or writing to the FileStream.

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

public:
virtual void Lock(
	long long position, 
	long 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.

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 file and directory operations, 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.

using namespace System;
using namespace System::IO;
using namespace System::Text;
int main()
{
   UnicodeEncoding^ uniEncoding = gcnew UnicodeEncoding;
   String^ lastRecordText = "The last processed record number was: ";
   int textLength = uniEncoding->GetByteCount( lastRecordText );
   int recordNumber = 13;
   int byteCount = uniEncoding->GetByteCount( recordNumber.ToString() );
   String^ tempString;

   FileStream^ fileStream = gcnew FileStream( "Test#@@#.dat",FileMode::OpenOrCreate,FileAccess::ReadWrite,FileShare::ReadWrite );

   try
   {

      // Write the original file data. 
      if ( fileStream->Length == 0 )
      {
         tempString = String::Concat( lastRecordText, recordNumber.ToString() );
         fileStream->Write( uniEncoding->GetBytes( tempString ), 0, uniEncoding->GetByteCount( tempString ) );
      }

      // Allow the user to choose the operation.
      Char consoleInput = 'R';
      array<Byte>^readText = gcnew array<Byte>(fileStream->Length);
      while ( consoleInput != 'X' )
      {
         Console::Write( "\nEnter 'R' to read, 'W' to write, 'L' to " 
         "lock, 'U' to unlock, anything else to exit: " );
         if ( (tempString = Console::ReadLine())->Length == 0 )
         {
            break;
         }
         consoleInput = Char::ToUpper( tempString[0] );
         switch ( consoleInput )
         {
            case 'R':
               try
               {
                  fileStream->Seek( 0, SeekOrigin::Begin );
                  fileStream->Read( readText, 0, (int)fileStream->Length );
                  tempString = gcnew String( uniEncoding->GetChars( readText, 0, readText->Length ) );
                  Console::WriteLine( tempString );
                  recordNumber = Int32::Parse( tempString->Substring( tempString->IndexOf( ':' ) + 2 ) );
               }
               // Catch the IOException generated if the  
               // specified part of the file is locked. 
               catch ( IOException^ e ) 
               {
                  Console::WriteLine( "{0}: The read " 
                  "operation could not be performed " 
                  "because the specified part of the " 
                  "file is locked.", e->GetType()->Name );
               }

               break;

            // Update the file. 
            case 'W':
               try
               {
                  fileStream->Seek( textLength, SeekOrigin::Begin );
                  fileStream->Read( readText, textLength - 1, byteCount );
                  tempString = gcnew String( uniEncoding->GetChars( readText, textLength - 1, byteCount ) );
                  recordNumber = Int32::Parse( tempString ) + 1;
                  fileStream->Seek( textLength, SeekOrigin::Begin );
                  fileStream->Write( uniEncoding->GetBytes( recordNumber.ToString() ), 0, byteCount );
                  fileStream->Flush();
                  Console::WriteLine( "Record has been updated." );
               }
               // Catch the IOException generated if the  
               // specified part of the file is locked. 
               catch ( IOException^ e ) 
               {
                  Console::WriteLine( "{0}: The write operation could not " 
                  "be performed because the specified " 
                  "part of the file is locked.", e->GetType()->Name );
               }


               break;

            // Lock the specified part of the file. 
            case 'L':
               try
               {
                  fileStream->Lock( textLength - 1, byteCount );
                  Console::WriteLine( "The specified part " 
                  "of file has been locked." );
               }
               catch ( IOException^ e ) 
               {
                  Console::WriteLine( "{0}: The specified part of file is" 
                  " already locked.", e->GetType()->Name );
               }

               break;

            // Unlock the specified part of the file. 
            case 'U':
               try
               {
                  fileStream->Unlock( textLength - 1, byteCount );
                  Console::WriteLine( "The specified part " 
                  "of file has been unlocked." );
               }
               catch ( IOException^ e ) 
               {
                  Console::WriteLine( "{0}: The specified part of file is " 
                  "not locked by the current process.", e->GetType()->Name );
               }

               break;

            default:

               // Exit the program.
               consoleInput = 'X';
               break;
         }
      }
   }
   finally
   {
      fileStream->Close();
   }

}

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft