Export (0) Print
Expand All
1 out of 4 rated this helpful - Rate this topic

FileStream.Lock Method

Prevents other processes from changing the FileStream while permitting read access.

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

public virtual void Lock (
	long position,
	long length
)
public void Lock (
	long position, 
	long length
)
public function Lock (
	position : long, 
	length : long
)

Parameters

position

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

length

The range to be locked.

Exception typeCondition

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.

The following table lists examples of other typical or related I/O tasks.

To do this...

See the example in this topic...

Create a text file.

How to: Write Text to a File

Write to a text file.

How to: Write Text to a File

Read from a text file.

How to: Read Text from a File

Append text to a file.

How to: Open and Append to a Log File

File.AppendText

FileInfo.AppendText

Rename or move a file.

File.Move

FileInfo.MoveTo

Copy a file.

File.Copy

FileInfo.CopyTo

Get the size of a directory.

FileInfo.Length

Get the attributes of a file.

File.GetAttributes

Set the attributes of a file.

File.SetAttributes

Create a subdirectory.

CreateSubdirectory

Read from a binary file.

How to: Read and Write to a Newly Created Data File

Write to a binary file.

How to: Read and Write to a Newly Created Data File

See the files in a directory.

Name

Sort files in a directory by size.

GetFileSystemInfos

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

import System.*;
import System.IO.*;
import System.Text.*;

class FStreamLock
{
    public static void main(String[] args)
    {
        UnicodeEncoding uniEncoding =  new UnicodeEncoding();
        String lastRecordText = "The last processed record number was: ";
        int textLength = uniEncoding.GetByteCount(lastRecordText);
        int recordNumber = 13;
        int byteCount = uniEncoding.GetByteCount(
            (new Integer(recordNumber)).ToString());
        String tempString;
                    
        FileStream fileStream =  new FileStream
            ("Test#@@#.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite,
            FileShare.ReadWrite);
        try {
            // Write the original file data.
            if ( fileStream.get_Length() == 0  ) {
                tempString = lastRecordText +(
                    new Integer( recordNumber)).ToString();
                fileStream.Write(uniEncoding.GetBytes(tempString),
                    0, uniEncoding.GetByteCount(tempString));
            }

            // Allow the user to choose the operation.
            char consoleInput = 'R';
            ubyte readText[] = new ubyte[(int) fileStream.get_Length() ];
            while((consoleInput != 'X')) {
                Console.Write(("\nEnter 'R' to read,'W' to write, 'L' to "
                    + "lock, 'U' to unlock, anything else to exit: "));
                if (((String)(tempString =
                        Console.ReadLine())).get_Length() == 0) {
                    break ;
                }
                consoleInput = Char.ToUpper( tempString.get_Chars(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.get_Length()));
                            tempString = new 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().get_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 = Int32.Parse(tempString)+1;
                            fileStream.Seek(textLength, SeekOrigin.Begin);
                            fileStream.Write(uniEncoding.GetBytes(
                                (new Integer( 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().get_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().get_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().get_Name());
                        }
                        break;

                    // Exit the program.
                    default :                        
                        // Exit the program.
                        consoleInput = 'X';
                        break;
                }                    
            }
        }
        finally {
            fileStream.Dispose();
        }
    } //main
} //FStreamLock

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

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

.NET Framework

Supported in: 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.