C# I/O流: FileStream

Table of contents

1. FileStream

二.Flush, Close , Dispose,using

3. Enumerate SeekOrigin

4. Creation of FileStream

5. Properties of FileStream

6. The method of FileStream:

1. Asynchronous write

2. Synchronous write

3. Asynchronous read

4. Synchronous read

5.Seek

6.SetLength

7. Other


1. FileStream

The FileStream class is mainly used for reading and writing files. It can not only read and write ordinary text files, but also read files in different formats such as image files and sound files.

二.Flush, Close , Dispose,using

Flush(), Close(), Dispose(), using(){}
Before looking at these four differences, you must first know the file buffer

Data output from memory to disk will be sent to the buffer in memory first, and then sent to disk together after the buffer is filled.
If data is read from the disk to the computer, the data read from the disk file is input to the memory buffer, and then the data is sent from the buffer to the program data area one by one.
The buffer is to improve the speed of reading and writing

1. Flush() is to clear the buffer and write the contents of the buffer to the file
2. Close() is

public virtual void Close()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}

3. Dispose() is

public void Dispose()
{
this.Close();
}

4. When using(){} ends, Dispose() will be called automatically

3. Enumerate SeekOrigin

Begin 0     
specifies where the stream begins.

Current 1     
specifies the current position in the stream.

End 2     
specifies where the stream ends.

4. Creation of FileStream

1.FileStream创建
        FileStream file = new FileStream(path, FileMode.Create);

2.File创建
        FileStream file1 = File.Create(path);
        FileStream file2 = File.Open(path, FileMode.Create);
        FileStream file3 = File.OpenRead(path);
        FileStream file4 = File.OpenWrite(path);

3.Fileinfo创建
        FileInfo fileInfo = new FileInfo(path);
        FileStream file5 = fileInfo.Create();
        FileStream file6 = fileInfo.Open(FileMode.Create);
        FileStream file7 = fileInfo.OpenRead();
        FileStream file8 = fileInfo.OpenWrite();

5. Properties of FileStream

CanRead     
gets a value indicating whether the current stream supports reading.

FileStream file = new FileStream(string path, FileMode mode, FileAccess access)
CanRead = false when access == FileAccess.Write or stream is closed;
CanRead = true when access == FileAccess.Read || access == FileAccess.ReadWrite;

CanWrite     
gets a value indicating whether the current stream supports writing.

FileStream file = new FileStream(string path, FileMode mode, FileAccess access)
CanWrite = true when access == FileAccess.Write || access == FileAccess.ReadWrite;
CanRead = false when access == FileAccess.Read or the stream is closed;

CanSeek     
gets a value indicating whether the current stream supports seeking.

CanSeek = false when stream is closed;

IsAsync     
gets a value indicating whether the FileStream was opened asynchronously or synchronously.

Length     
gets the length of the stream in bytes.

Name     
gets the absolute path of the opened file in the FileStream.

Position
gets or sets the current position of this stream.

Similar to Seek(),
the difference is:
1. Obtaining
        Position obtains the end position of the current stream.
        Seek() obtains the position at which reading starts this time.

2. Setting
        Seek() can set the position without knowing the length of the stream

For example:

    public void Seek() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            byte[] array = new byte[4];
            file.Read(array, 0, 4);
            string str1 = System.Text.Encoding.Default.GetString(array);
            Console.WriteLine($"先读两个:{str1} 流的位置 :{file.Position}");

            long seekLength = file.Seek(4, SeekOrigin.Current);
            byte[] array1 = new byte[1024];
            file.Read(array1, 0, 1024);
            string str = System.Text.Encoding.Default.GetString(array1);
            Console.WriteLine($"用SeekOrigin.Current 4 :{str} 流的位置 :{file.Position} seekLength:{seekLength}");

            file.Flush();
        }
    }

Print:

The space is
byte[] array1 = new byte[1024]; the reason for this code

SafeFileHandle     
gets the SafeFileHandle object, which represents the operating system file handle of the file encapsulated by the current FileStream object.

6. The method of FileStream:

1. Asynchronous write

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)     
starts an asynchronous write operation. Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.
WriteAsync(Byte[], Int32, Int32, CancellationToken)     
asynchronously writes a sequence of bytes to the current stream, advances the current position in that stream by the number of bytes written, and monitors for cancellation requests.
EndWrite(IAsyncResult)     
ends the asynchronous write operation and blocks until the I/O operation is complete. (Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

public async void  AsyncWrite() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            string str = "当前流是否支持读取";
            byte[] array = System.Text.Encoding.Default.GetBytes(str);
            await file.WriteAsync(array, 0, array.Length);
            Console.WriteLine($"获取或设置此流的当前位置Write2:{file.Position}");
            file.Flush();
        }
    }

Print:


2. Synchronous write

Write(Byte[], Int32, Int32)     
writes a block of bytes to the file stream.
WriteByte(Byte)     
writes a byte to the current position in the file stream.

public void Write() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            string str = "当前流是否支持查找";
            byte[] array = System.Text.Encoding.Default.GetBytes(str);
            file.Write(array, 0, array.Length);
            Console.WriteLine($"获取或设置此流的当前位置Write1:{file.Position}");
            file.Flush();
        }
    }

Print:

3. Asynchronous read

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)     
starts an asynchronous read operation. Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.
EndRead(IAsyncResult)     
waits for the pending asynchronous read operation to complete. (Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)
ReadAsync(Byte[], Int32, Int32, CancellationToken)     
asynchronously reads a sequence of bytes from the current file stream, The byte array at which the offset starts, advances the position in the file stream by the number of bytes read, and monitors for cancellation requests.
 

public async void AsyncRead() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            byte[] array = new byte[1024];
            await file.ReadAsync(array, 0, 1024);
            string str = System.Text.Encoding.Default.GetString(array);
            Console.WriteLine(str);
            file.Flush();
        }
    }

Print:

4. Synchronous read

Read(Byte[], Int32, Int32)     
reads a block of bytes from the stream and writes that data into the given buffer.
ReadByte()     
reads one byte from the file and advances the read position by one byte.

public void Read() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            byte[] array = new byte[1024];
            int length = file.Read(array, 0, 1024);
            string str = System.Text.Encoding.Default.GetString(array);
            Console.WriteLine(str);
            file.Flush();
        }
    }

Print:

5.Seek

Seek(Int64, SeekOrigin)     
Sets the current position of this stream to the given value.
1. Seek Origin. Begin

public void Seek() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            long seekLength = file.Seek(8, SeekOrigin.Begin);
            byte[] array = new byte[1024];
            file.Read(array, 0, 1024);
            string str = System.Text.Encoding.Default.GetString(array);
            Console.WriteLine(str);
            file.Flush();
        }
    }

Print:


2.SeekOrigin.End

public void Seek() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            long seekLength = file.Seek(-8, SeekOrigin.End);
            byte[] array = new byte[1024];
            file.Read(array, 0, 1024);
            string str = System.Text.Encoding.Default.GetString(array);
            Console.WriteLine(str);
            file.Flush();
        }
    }

Print:


3.SeekOrigin.Current

public void Seek() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            byte[] array = new byte[4];
            file.Read(array, 0, 4);
            string str1 = System.Text.Encoding.Default.GetString(array);
            Console.WriteLine($"先读两个:{str1}");

            long seekLength = file.Seek(4, SeekOrigin.Current);
            byte[] array1 = new byte[1024];
            file.Read(array1, 0, 1024);
            string str = System.Text.Encoding.Default.GetString(array1);
            Console.WriteLine($"用SeekOrigin.Current 4 :{str}");

            file.Flush();
        }
    }

Print:

6.SetLength

SetLength(Int64)     
sets the length of this stream to the given value.

public void SetLength() {
        using(file = new FileStream(path, FileMode.OpenOrCreate)) {
            Console.WriteLine($"获取流的长度(以字节为单位):{file.Length}");
            file.SetLength(100);
            Console.WriteLine($"获取流的长度(以字节为单位):{file.Length}");
            file.Flush();
        }
    }

Print:

7. Other

Lock(Int64, Int64)     
prevents other processes from reading or writing to the FileStream.
Unlock(Int64, Int64)     
allows other processes to access all or part of a file that was previously locked.

Flush()     
clears this stream's buffer, causing all buffered data to be written to the file.
Flush (Boolean)     
Flushes this stream's buffers, writing all buffered data to the file, and also flushes any intermediate file buffers.
FlushAsync(CancellationToken)     
flushes all buffers for this stream asynchronously, causing all buffered data to be written to the underlying device, and monitors for cancellation requests.

Dispose(Boolean)     
Releases unmanaged resources occupied by the FileStream, and may additionally release managed resources.

Guess you like

Origin blog.csdn.net/SmillCool/article/details/127791714