System.IO.FileStream.WriteAsync C# (CSharp) Method

WriteAsync() public method

public WriteAsync ( byte buffer, int offset, int count, CancellationToken cancellationToken ) : Task
buffer byte
offset int
count int
cancellationToken CancellationToken
return Task
        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            if (buffer == null)
                throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
            if (offset < 0)
                throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
            if (count < 0)
                throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
            if (buffer.Length - offset < count)
                throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);

            // If we have been inherited into a subclass, the following implementation could be incorrect
            // since it does not call through to Write() or WriteAsync() which a subclass might have overridden.  
            // To be safe we will only use this implementation in cases where we know it is safe to do so,
            // and delegate to our base class (which will call into Write/WriteAsync) when we are not sure.
            if (GetType() != typeof(FileStream))
                return base.WriteAsync(buffer, offset, count, cancellationToken);

            if (cancellationToken.IsCancellationRequested)
                return Task.FromCanceled(cancellationToken);

            if (IsClosed)
                throw Error.GetFileNotOpen();

            return WriteAsyncInternal(buffer, offset, count, cancellationToken);
        }

Usage Example

Example #1
0
        public void NegativeOffsetThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, 1)));

                // buffer is checked first
                Assert.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, 1)));
            }
        }
All Usage Examples Of System.IO.FileStream::WriteAsync