次の方法で共有


FileStream.Lock メソッド

読み取りアクセスを許可している間に他のプロセスによって FileStream が変更されるのを防ぎます。

Public Overridable Sub Lock( _
   ByVal position As Long, _   ByVal length As Long _)
[C#]
public virtual void Lock(longposition,longlength);
[C++]
public: virtual void Lock(__int64position,__int64length);
[JScript]
public function Lock(
   position : long,length : long);

パラメータ

  • position
    ロックする範囲の先頭。このパラメータの値は、0 (ゼロ) 以上にする必要があります。
  • length
    ロックする範囲。

例外

例外の種類 条件
ArgumentOutOfRangeException position または length が負の値です。
ObjectDisposedException ファイルが閉じています。

解説

その他の一般的な I/O タスクまたは関連する I/O タスクの例を次の表に示します。

実行するタスク 参考例があるトピック
テキスト ファイルを作成する。 ファイルへのテキストの書き込み
テキスト ファイルに書き込む。 ファイルへのテキストの書き込み
テキスト ファイルから読み取る。 ファイルからのテキストの読み取り
テキストをファイルに追加する。 ログ ファイルのオープンと追加

File.AppendText

FileInfo.AppendText

ファイルの名前を変更、またはファイルを移動する。 File.Move

FileInfo.MoveTo

ファイルをコピーする。 File.Copy

FileInfo.CopyTo

ディレクトリのサイズを取得する。 FileInfo.Length
ファイルの属性を取得する。 File.GetAttributes
ファイルの属性を設定する。 File.SetAttributes
サブディレクトリを作成する。 CreateSubdirectory
バイナリ ファイルから読み取る。 新しく作成したデータ ファイルの読み取りと書き込み
バイナリ ファイルに書き込む。 新しく作成したデータ ファイルの読み取りと書き込み
ディレクトリ内のファイルを参照する。 Name
ディレクトリ内のファイルをサイズ順に並べ替える。 GetFileSystemInfos

使用例

[Visual Basic, C#, C++] 次に示すのは、ファイルの一部をロックするコード例です。他のプロセスがアクセスを試みると、たとえそのファイルへの読み取り/書き込みアクセス権があっても、そのアクセスは拒否されます。プログラムを複数のコマンド ウィンドウで同時に実行し、それぞれに異なるコンソール入力オプションを使用して結果を確認してください。

 
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

[C#] 
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;
                }
            }
        }
    }
}

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
using namespace System::Text;

void main()
{
    UnicodeEncoding* uniEncoding = new UnicodeEncoding();
    String* lastRecordText = 
        S"The last processed record number was: ";
    int textLength = uniEncoding->GetByteCount(lastRecordText);
    int recordNumber = 13;
    int byteCount = 
        uniEncoding->GetByteCount(recordNumber.ToString());
    String* tempString;

    FileStream* fileStream = new FileStream(
        S"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';
        Byte readText __gc[] = new Byte __gc[fileStream->Length];
        while(consoleInput != 'X')
        {
            Console::Write(
                S"\nEnter 'R' to read, 'W' to write, 'L' to "  
                S"lock, 'U' to unlock, anything else to exit: ");

            if((tempString = Console::ReadLine())->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->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(S"{0}: The read " 
                            S"operation could not be performed " 
                            S"because the specified part of the " 
                            S"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 = Int32::Parse(tempString) + 1;
                        fileStream->Seek(
                            textLength, SeekOrigin::Begin);
                        fileStream->Write(uniEncoding->GetBytes(
                            recordNumber.ToString()), 0, byteCount);
                        fileStream->Flush();
                        Console::WriteLine(
                            S"Record has been updated.");
                    }

                    // Catch the IOException* generated if the 
                    // specified part of the file is locked.
                    catch(IOException* e)
                    {
                        Console::WriteLine(
                            S"{0}: The write operation could not " 
                            S"be performed because the specified " 
                            S"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(S"The specified part " 
                            S"of file has been locked.");
                    }
                    catch(IOException* e)
                    {
                        Console::WriteLine(
                            S"{0}: The specified part of file is" 
                            S" already locked.", e->GetType()->Name);
                    }
                    break;

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

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

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ

参照

FileStream クラス | FileStream メンバ | System.IO 名前空間 | 入出力操作 | ファイルからのテキストの読み取り | ファイルへのテキストの書き込み