본문 바로가기
C#

[C#] FileStream

by DANEW 2023. 11. 20.

FileStream 클래스

 

FileStream Class (System.IO)

Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.

learn.microsoft.com

namespace System.IO
{
    public class FileStream : Stream
    {
        // 생성자
        public FileStream(string path, FileMode mode);
        public FileStream(string path, FileMode mode, FileAccess access);
        public FileStream(string path, FileMode mode, FileAccess access, FileShare share);
        public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize);
        public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync);
        public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options);
        public FileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options);
        public FileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity);
        public FileStream(SafeFileHandle handle, FileAccess access);
        public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize);
        public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync);

        // 읽기
        public override bool CanRead { get; }
        public override int Read(byte[] array, int offset, int count);
        public override int ReadByte();
        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
        public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject);
        public override int EndRead(IAsyncResult asyncResult);

        // 쓰기
        public override bool CanWrite { get; }
        public override void Write(byte[] array, int offset, int count);
        public override void WriteByte(byte value);
        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
        public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject);
        public override void EndWrite(IAsyncResult asyncResult);

        // 탐색
        public override bool CanSeek { get; }
        public override long Position { get; set; }
        public override long Length { get; }
        public override void SetLength(long value);
        public override long Seek(long offset, SeekOrigin origin);
        
        // 배출, 닫기
        public override void Flush();
        public virtual void Flush(bool flushToDisk);
        public override Task FlushAsync(CancellationToken cancellationToken);
        protected override void Dispose(bool disposing);

        // 기타
        public string Name { get; }
        public virtual bool IsAsync { get; }
        public virtual SafeFileHandle SafeFileHandle { get; }
        public FileSecurity GetAccessControl();
        public void SetAccessControl(FileSecurity fileSecurity);
        public virtual void Lock(long position, long length);
        public virtual void Unlock(long position, long length);

        // 폐기
        public FileStream(IntPtr handle, FileAccess access);
        public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize);
        public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
        public virtual IntPtr Handle { get; }
    }
}

File 클래스의 정적 퍼사드 메서드 사용하여 객체 생성

- File.OpenRead (읽기)
- File.OpenWrite (쓰기) - 파일이 있다면 기존 파일은 폐기
- File.Create (읽기/쓰기) - 덮어쓰기, 시작 포인터는 0

 

생성자를 사용

path

- 절대 주소 & 상대 주소 & UNC 경로 등...
- 현재 디렉터리: Environment.CurrentDirectory, 가급적 쓰지 말 것
- 실행 파일이 위치한 디렉터리: AppDomain.CurrentDomain.BaseDirectory
- Path.Combine을 통해 디렉터리와 파일명을 이어줌

 

mode

- 파일 개방과 관련된 모드를 지정
- System.IO.FileMode 열거형
 * CreateNew: 파일을 새로 만듬, 파일이 이미 있다면 예외 발생
 * Create: 파일을 새로 만듬. 기존 파일이 있다면 폐기 File.Create()와 같음
 * Open: 파일이 없다면 예외 발생, File.OpenRead()와 같음
 * OpenOrCreate: 파일이 있다면 그대로 두고, 파일이 없다면 새로 만듬, 파일 포인터는 0, File.OpenWrite()와 같음
 * Truncate: 파일이 있건 없건 새로 만듬
 * Append: 쓰기 전용, 파일 포인터는 파일의 끝

access

- 읽기 / 쓰기 권한 지정
- System.IO.FileAccess 열거형
 * Read: 읽기
 * Write: 쓰기
 * ReadWrite: 읽기 / 쓰기

반응형

rights

- access 대신 사용 가능, 좀 더 자세한 파일 권한 지정... 인거 같은데 책에는 언급이 없음

 

FileSystemRights Enum (System.Security.AccessControl)

Defines the access rights to use when creating access and audit rules.

 

 

 

learn.microsoft.com

namespace System.Security.AccessControl
{
    [Flags]
    public enum FileSystemRights
    {
        ReadData = 1,
        ListDirectory = 1,
        WriteData = 2,
        CreateFiles = 2,
        AppendData = 4,
        CreateDirectories = 4,
        ReadExtendedAttributes = 8,
        WriteExtendedAttributes = 16,
        ExecuteFile = 32,
        Traverse = 32,
        DeleteSubdirectoriesAndFiles = 64,
        ReadAttributes = 128,
        WriteAttributes = 256,
        Write = 278,
        Delete = 65536,
        ReadPermissions = 131072,
        Read = 131209,
        ReadAndExecute = 131241,
        Modify = 197055,
        ChangePermissions = 262144,
        TakeOwnership = 524288,
        Synchronize = 1048576,
        FullControl = 2032127
    }
}

share

- 사용중인 스트림에 다른 프로세스가 어떤 권한으로 접근 할 수 있는지 결정
- 읽기 / 쓰기 공유시 Lock으로 잠금을 걸고 사용 후 Unlock으로 잠금을 풀어줘야 함
- System.IO.FileShare 열거형
 * None: 권한 없음
 * Read: 읽기 가능, 기본 값
 * Write: 쓰기 가능
 * ReadWrite: Read | Write
 * Delete: 삭제 가능
 * Inheritable: 자식 프로세스에게 상속 가능한 핸들을 만듬

bufferSize

- 내부 버퍼의 크기
- 기본값은 4KB

useAsync

- 비동기 입출력을 운영체제에 맡길 것인지 나타냄

fileSecurity

- 새 파일에 부여햘 사용자 및 역할(role) 권한들을 서술
- 책에 설명도 적고 자세히 알아보기 힘들어서 일단은 패스

 

FileSecurity Class (System.Security.AccessControl)

Represents the access control and audit security for a file. This class cannot be inherited.

learn.microsoft.com

fileOption

- System.IO.FileOption 열거형
 * WriteThrough: Write-Behind Caching(이게 뭐지?)을 비활성화하라고 OS에 요청
 * None: 옵션 없음
 * Encrypted: OS 암호화 요청 (같은 유저 계정으로만 복호화 가능)
 * DeleteOnClose: 스트림 종료시 파일 자동 삭제
 * SequentialScan: 캐싱 힌트, 파일이 순차적으로 기록되어있음을 알려줌 
 * RandomAccess: 캐싱 힌트, 파일이 랜덤하게 여러 곳으로 분포되어있음을 알려줌
 * Asynchronous: 비동기적 읽기/쓰기 사용 (이걸 걸지 않아도 비동기 사용은 가능한듯?)

 

반응형

'C#' 카테고리의 다른 글

[C#] NamedPipeServerStream, NamedPipeClientStream  (0) 2023.12.04
[C#] PipeStream  (0) 2023.12.01
[C#] MemoryStream  (0) 2023.11.24
[C#] Stream  (0) 2023.11.17
[C#] Task  (0) 2023.11.06
[C#] Thread  (0) 2023.11.01
[C#] Stopwatch  (0) 2023.10.30
[C#] PerformanceCounter, PerformanceCounterCategory  (0) 2023.10.28