다음을 통해 공유


FileStream.Lock 메서드

읽기 권한을 허용할 때 다른 프로세스가 FileStream을 변경하지 못하게 합니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
Public Overridable Sub Lock ( _
    position As Long, _
    length As Long _
)
‘사용 방법
Dim instance As FileStream
Dim position As Long
Dim length As Long

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

매개 변수

  • position
    잠글 범위의 시작 부분입니다. 이 매개 변수의 값은 0보다 크거나 같아야 합니다.
  • length
    잠글 범위입니다.

예외

예외 형식 조건

ArgumentOutOfRangeException

position 또는 length가 음수인 경우

ObjectDisposedException

파일이 닫힌 경우

IOException

다른 프로세스에서 파일의 일부를 잠궜기 때문에 이 프로세스에서 파일에 액세스할 수 없는 경우

설명

다음 표에서는 일반적인 예 또는 관련된 I/O 작업의 예를 보여 줍니다.

수행 작업

참조 항목

텍스트 파일을 만듭니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에 씁니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에서 읽습니다.

방법: 파일의 텍스트 읽기

파일에 텍스트를 추가합니다.

방법: 로그 파일 열기 및 추가

File.AppendText

FileInfo.AppendText

파일 이름을 바꾸거나 이동합니다.

File.Move

FileInfo.MoveTo

파일을 복사합니다.

File.Copy

FileInfo.CopyTo

디렉터리 크기를 가져옵니다.

FileInfo.Length

파일 특성을 가져옵니다.

File.GetAttributes

파일의 특성을 설정합니다.

File.SetAttributes

하위 디렉터리를 만듭니다.

CreateSubdirectory

이진 파일에서 읽습니다.

방법: 새로 만든 데이터 파일 읽기 및 쓰기

이진 파일에 씁니다.

방법: 새로 만든 데이터 파일 읽기 및 쓰기

디렉터리의 파일을 참조하십시오.

Name

디렉터리의 파일을 크기순으로 정렬합니다.

GetFileSystemInfos

예제

다음 코드 예제에서는 파일의 일부를 잠궈서 다른 프로세스에서 해당 파일에 대해 읽기/쓰기 권한이 있어도 해당 부분에는 액세스할 수 없도록 하는 방법을 보여 줍니다. 서로 다른 명령 창에서 프로그램을 동시에 실행하고 서로 다른 콘솔 입력 옵션을 사용하여 조사합니다.

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

}
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

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

참고 항목

참조

FileStream 클래스
FileStream 멤버
System.IO 네임스페이스

기타 리소스

파일 및 스트림 I/O
방법: 파일의 텍스트 읽기
방법: 파일에 텍스트 쓰기