Compartir vía


FileStream.Lock(Int64, Int64) Método

Definición

Impide que otros procesos lean de FileStream o escriban en él.

public:
 virtual void Lock(long position, long length);
public virtual void Lock (long position, long length);
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("macos")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public virtual void Lock (long position, long length);
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("macos")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
[System.Runtime.Versioning.UnsupportedOSPlatform("freebsd")]
public virtual void Lock (long position, long length);
abstract member Lock : int64 * int64 -> unit
override this.Lock : int64 * int64 -> unit
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("macos")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
abstract member Lock : int64 * int64 -> unit
override this.Lock : int64 * int64 -> unit
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("macos")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("freebsd")>]
abstract member Lock : int64 * int64 -> unit
override this.Lock : int64 * int64 -> unit
Public Overridable Sub Lock (position As Long, length As Long)

Parámetros

position
Int64

Comienzo del intervalo que se va a bloquear. El valor de este parámetro debe ser igual o mayor que cero (0).

length
Int64

El intervalo que se va a bloquear.

Atributos

Excepciones

position o length es negativo.

El archivo se cierra.

El proceso no puede obtener acceso al archivo porque otro proceso ha bloqueado una parte de este.

Ejemplos

En el ejemplo de código siguiente se muestra cómo bloquear parte de un archivo para que otro proceso no pueda tener acceso a esa parte del archivo aunque tenga acceso de lectura y escritura al archivo. Ejecute el programa simultáneamente en diferentes ventanas de comandos e investigue con las distintas opciones de entrada de la consola.

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();
   }

}
using System;
using System.IO;
using System.Text;

class FStreamLock
{
    static void Main()
    {
        UnicodeEncoding uniEncoding = new 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;

        using(FileStream fileStream = new FileStream(
            "Test#@@#.dat", FileMode.OpenOrCreate,
            FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            // Write the original file data.
            if(fileStream.Length == 0)
            {
                tempString =
                    lastRecordText + recordNumber.ToString();
                fileStream.Write(uniEncoding.GetBytes(tempString),
                    0, uniEncoding.GetByteCount(tempString));
            }

            // Allow the user to choose the operation.
            char consoleInput = 'R';
            byte[] readText = new 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)
                {
                    // Read data from the file and
                    // write it to the console.
                    case 'R':
                        try
                        {
                            fileStream.Seek(0, SeekOrigin.Begin);
                            fileStream.Read(
                                readText, 0, (int)fileStream.Length);
                            tempString = new String(
                                uniEncoding.GetChars(
                                readText, 0, readText.Length));
                            Console.WriteLine(tempString);
                            recordNumber = int.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 = new String(
                                uniEncoding.GetChars(
                                readText, textLength - 1, byteCount));
                            recordNumber = int.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;

                    // Exit the program.
                    default:
                        consoleInput = 'X';
                        break;
                }
            }
        }
    }
}
open System
open System.IO
open System.Text

let uniEncoding = UnicodeEncoding()
let lastRecordText = "The last processed record number was: "
let textLength = uniEncoding.GetByteCount lastRecordText
let mutable recordNumber = 13
let byteCount = string recordNumber |> uniEncoding.GetByteCount

do
    use fileStream =
        new FileStream("Test#@@#.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)

    // Write the original file data.
    if fileStream.Length = 0 then
        let tempString = lastRecordText + string recordNumber
        fileStream.Write(uniEncoding.GetBytes tempString, 0, uniEncoding.GetByteCount tempString)


    // Allow the user to choose the operation.
    let mutable consoleInput = 'R'
    let readText = int fileStream.Length |> Array.zeroCreate

    while consoleInput <> 'X' do
        printf "\nEnter 'R' to read, 'W' to write, 'L' to lock, 'U' to unlock, anything else to exit: "

        let mutable tempString = stdin.ReadLine()

        if tempString.Length = 0 then
            consoleInput <- 'X'
        else
            consoleInput <- Char.ToUpper tempString[0]

            match consoleInput with
            | 'R' ->
                // Read data from the file and
                // write it to the console.
                try
                    fileStream.Seek(0, SeekOrigin.Begin) |> ignore
                    fileStream.Read(readText, 0, int fileStream.Length) |> ignore
                    tempString <- String(uniEncoding.GetChars readText, 0, readText.Length)
                    printfn $"{tempString}"
                    recordNumber <- tempString.IndexOf ':' + 2 |> tempString.Substring |> Int32.Parse

                // Catch the IOException generated if the
                // specified part of the file is locked.
                with :? IOException as e ->

                    printfn
                        $"{e.GetType().Name}: The read operation could not be performed because the specified part of the file is locked."

            | 'W' ->
                // Update the file.
                try

                    fileStream.Seek(textLength, SeekOrigin.Begin) |> ignore
                    fileStream.Read(readText, textLength - 1, byteCount) |> ignore
                    tempString <- String(uniEncoding.GetChars readText, textLength - 1, byteCount)
                    recordNumber <- Int32.Parse tempString + 1
                    fileStream.Seek(textLength, SeekOrigin.Begin) |> ignore
                    fileStream.Write(string recordNumber |> uniEncoding.GetBytes, 0, byteCount)
                    fileStream.Flush()
                    printfn "Record has been updated."

                // Catch the IOException generated if the
                // specified part of the file is locked.
                with :? IOException as e ->
                    printfn
                        $"{e.GetType().Name}: The write operation could not be performed because the specified part of the file is locked."

            // Lock the specified part of the file.
            | 'L' ->
                try
                    fileStream.Lock(textLength - 1 |> int64, byteCount)
                    printfn "The specified part of file has been locked."
                with :? IOException as e ->
                    printfn $"{e.GetType().Name}: The specified part of file is already locked."

            // Unlock the specified part of the file.
            | 'U' ->
                try
                    fileStream.Unlock(textLength - 1 |> int64, byteCount)
                    printfn "The specified part of file has been unlocked."

                with :? IOException as e ->
                    printfn $"{e.GetType().Name}: The specified part of file is not locked by the current process."

            // Exit the program.
            | _ -> consoleInput <- 'X'
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

Comentarios

El bloqueo de un intervalo de una secuencia de archivos proporciona a los subprocesos del proceso de bloqueo acceso exclusivo a ese intervalo de la secuencia de archivos.

Para obtener una lista de las operaciones comunes de archivos y directorios, consulte Tareas comunes de E/S.

Se aplica a

Consulte también