2 using Microsoft.Win32.SafeHandles;
17 private sealed
class FileStreamReadWriteTask<
T> :
Task<T>
23 internal FileStreamAsyncResult _asyncResult;
27 _cancellationToken = cancellationToken;
31 internal const int DefaultBufferSize = 4096;
33 private const bool _canUseAsync =
true;
35 private byte[] _buffer;
37 private string _fileName;
39 private bool _isAsync;
41 private bool _canRead;
43 private bool _canWrite;
45 private bool _canSeek;
47 private bool _exposedHandle;
55 private int _writePos;
57 private int _bufferSize;
64 private long _appendStart;
70 private static Action<object> s_cancelReadHandler;
72 private static Action<object> s_cancelWriteHandler;
74 private const int FILE_ATTRIBUTE_NORMAL = 128;
76 private const int FILE_ATTRIBUTE_ENCRYPTED = 16384;
78 private const int FILE_FLAG_OVERLAPPED = 1073741824;
80 internal const int GENERIC_READ =
int.MinValue;
82 private const int GENERIC_WRITE = 1073741824;
84 private const int FILE_BEGIN = 0;
86 private const int FILE_CURRENT = 1;
88 private const int FILE_END = 2;
90 internal const int ERROR_BROKEN_PIPE = 109;
92 internal const int ERROR_NO_DATA = 232;
94 private const int ERROR_HANDLE_EOF = 38;
96 private const int ERROR_INVALID_PARAMETER = 87;
98 private const int ERROR_IO_PENDING = 997;
125 public override long Length 127 [SecuritySafeCritical]
130 if (_handle.IsClosed)
132 __Error.FileNotOpen();
136 __Error.SeekNotSupported();
140 num = Win32Native.GetFileSize(_handle, out highSize);
144 if (lastWin32Error != 0)
146 __Error.WinIOError(lastWin32Error,
string.Empty);
149 long num2 = ((long)highSize << 32) | (uint)num;
150 if (_writePos > 0 && _pos + _writePos > num2)
152 num2 = _writePos + _pos;
162 [SecuritySafeCritical]
165 if (_fileName ==
null)
167 return Environment.GetResourceString(
"IO_UnknownFileName");
174 internal string NameInternal
178 if (_fileName ==
null)
180 return "<UnknownFileName>";
194 [SecuritySafeCritical]
197 if (_handle.IsClosed)
199 __Error.FileNotOpen();
203 __Error.SeekNotSupported();
207 VerifyOSHandlePosition();
209 return _pos + (_readPos - _readLen + _writePos);
219 FlushWrite(calledFromFinalizer:
false);
230 [Obsolete(
"This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
241 _exposedHandle =
true;
242 return _handle.DangerousGetHandle();
258 _exposedHandle =
true;
284 [SecuritySafeCritical]
309 [SecuritySafeCritical]
335 [SecuritySafeCritical]
337 : this(path, mode, access, share, 4096,
FileOptions.
None,
Path.GetFileName(path), bFromProxy: false)
363 [SecuritySafeCritical]
365 : this(path, mode, access, share, bufferSize,
FileOptions.
None,
Path.GetFileName(path), bFromProxy: false)
393 [SecuritySafeCritical]
395 : this(path, mode, access, share, bufferSize, options,
Path.GetFileName(path), bFromProxy: false)
422 [SecuritySafeCritical]
454 [SecuritySafeCritical]
457 object pinningHandle;
458 Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share, fileSecurity, out pinningHandle);
461 Init(path, mode, (
FileAccess)0, (
int)rights, useRights:
true, share, bufferSize, options, secAttrs,
Path.
GetFileName(path), bFromProxy:
false, useLongPath:
false, checkHost:
false);
465 if (pinningHandle !=
null)
497 [SecuritySafeCritical]
500 Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
501 Init(path, mode, (
FileAccess)0, (
int)rights, useRights:
true, share, bufferSize, options, secAttrs,
Path.
GetFileName(path), bFromProxy:
false, useLongPath:
false, checkHost:
false);
507 Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
508 Init(path, mode, access, 0, useRights:
false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, useLongPath:
false, checkHost:
false);
514 Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
515 Init(path, mode, access, 0, useRights:
false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, useLongPath, checkHost:
false);
519 internal FileStream(
string path,
FileMode mode,
FileAccess access,
FileShare share,
int bufferSize,
FileOptions options,
string msgPath,
bool bFromProxy,
bool useLongPath,
bool checkHost)
521 Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
522 Init(path, mode, access, 0, useRights:
false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, useLongPath, checkHost);
525 [SecuritySafeCritical]
526 private unsafe
void Init(
string path,
FileMode mode,
FileAccess access,
int rights,
bool useRights,
FileShare share,
int bufferSize,
FileOptions options, Win32Native.SECURITY_ATTRIBUTES secAttrs,
string msgPath,
bool bFromProxy,
bool useLongPath,
bool checkHost)
530 throw new ArgumentNullException(
"path", Environment.GetResourceString(
"ArgumentNull_Path"));
532 if (path.Length == 0)
534 throw new ArgumentException(Environment.GetResourceString(
"Argument_EmptyPath"));
537 _exposedHandle =
false;
540 if (mode < FileMode.CreateNew || mode >
FileMode.Append)
544 else if (!useRights && (access < FileAccess.Read || access >
FileAccess.ReadWrite))
548 else if (useRights && (rights < 1 || rights > 2032127))
558 throw new ArgumentOutOfRangeException(text, Environment.GetResourceString(
"ArgumentOutOfRange_Enum"));
560 if (options != 0 && (options & (
FileOptions)67092479) != 0)
562 throw new ArgumentOutOfRangeException(
"options", Environment.GetResourceString(
"ArgumentOutOfRange_Enum"));
566 throw new ArgumentOutOfRangeException(
"bufferSize", Environment.GetResourceString(
"ArgumentOutOfRange_NeedPosNum"));
572 throw new ArgumentException(Environment.GetResourceString(
"Argument_InvalidFileMode&AccessCombo", mode, access));
574 throw new ArgumentException(Environment.GetResourceString(
"Argument_InvalidFileMode&RightsCombo", mode, (
FileSystemRights)rights));
576 if (useRights && mode ==
FileMode.Truncate)
580 throw new ArgumentException(Environment.GetResourceString(
"Argument_InvalidFileModeTruncate&RightsCombo", mode, (
FileSystemRights)rights));
601 dwDesiredAccess = num;
605 dwDesiredAccess = rights;
607 int maxPathLength = useLongPath ? 32767 : (AppContextSwitches.BlockLongPaths ? 260 : 32767);
608 string text2 = _fileName =
Path.NormalizePath(path, fullCheck:
true, maxPathLength);
609 if ((!CodeAccessSecurityEngine.QuickCheckForAllDemands() || AppContextSwitches.UseLegacyPathHandling) && text2.StartsWith(
"\\\\.\\",
StringComparison.Ordinal))
611 throw new ArgumentException(Environment.GetResourceString(
"Arg_DevicesNotSupported"));
614 if ((!useRights && (access &
FileAccess.Read) != 0) || (useRights && (rights & 0x200A9) != 0))
618 throw new ArgumentException(Environment.GetResourceString(
"Argument_InvalidAppendMode"));
622 if (CodeAccessSecurityEngine.QuickCheckForAllDemands())
633 if ((!useRights && (access &
FileAccess.Write) != 0) || (useRights && (rights & 0xD0156) != 0) || (useRights && (rights & 0x100000) != 0 && mode ==
FileMode.OpenOrCreate))
641 }, checkForDuplicates:
false, needFullPath:
false);
644 bool flag2 = mode ==
FileMode.Append;
657 int num2 = (int)options;
659 int errorMode = Win32Native.SetErrorMode(1);
662 string text3 = text2;
665 text3 =
Path.AddLongPathPrefix(text3);
667 _handle = Win32Native.SafeCreateFile(text3, dwDesiredAccess, share, secAttrs, mode, num2, IntPtr.Zero);
668 if (_handle.IsInvalid)
671 if (num3 == 3 && text2.Equals(
Directory.InternalGetDirectoryRoot(text2)))
689 __Error.WinIOError(num3, _fileName);
693 __Error.WinIOError(num3, msgPath);
699 Win32Native.SetErrorMode(errorMode);
701 int fileType = Win32Native.GetFileType(_handle);
705 throw new NotSupportedException(Environment.GetResourceString(
"NotSupported_FileStreamOnNonFiles"));
725 throw new IOException(Environment.GetResourceString(
"IO.IO_BindHandleFailed"));
735 _canRead = ((rights & 1) != 0);
736 _canWrite = ((rights & 2) != 0 || (rights & 4) != 0);
741 _bufferSize = bufferSize;
763 [Obsolete(
"This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
765 : this(handle, access, ownsHandle: true, 4096, isAsync: false)
779 [Obsolete(
"This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
781 : this(handle, access, ownsHandle, 4096, isAsync: false)
796 [Obsolete(
"This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
798 : this(handle, access, ownsHandle, bufferSize, isAsync: false)
816 [SecuritySafeCritical]
817 [Obsolete(
"This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
820 : this(new
SafeFileHandle(handle, ownsHandle), access, bufferSize, isAsync)
832 [SecuritySafeCritical]
834 : this(handle, access, 4096, isAsync: false)
847 [SecuritySafeCritical]
849 : this(handle, access, bufferSize, isAsync: false)
864 [SecuritySafeCritical]
868 if (handle.IsInvalid)
873 _exposedHandle =
true;
874 if (access < FileAccess.Read || access >
FileAccess.ReadWrite)
882 int fileType = Win32Native.GetFileType(_handle);
886 _canSeek = (fileType == 1);
887 _bufferSize = bufferSize;
892 _isPipe = (fileType == 3);
909 else if (fileType != 3)
911 VerifyHandleIsSync();
923 [SecuritySafeCritical]
924 private static Win32Native.SECURITY_ATTRIBUTES GetSecAttrs(
FileShare share)
926 Win32Native.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES =
null;
927 if ((share &
FileShare.Inheritable) != 0)
929 sECURITY_ATTRIBUTES =
new Win32Native.SECURITY_ATTRIBUTES();
930 sECURITY_ATTRIBUTES.nLength =
Marshal.
SizeOf(sECURITY_ATTRIBUTES);
931 sECURITY_ATTRIBUTES.bInheritHandle = 1;
933 return sECURITY_ATTRIBUTES;
936 [SecuritySafeCritical]
937 private unsafe
static Win32Native.SECURITY_ATTRIBUTES GetSecAttrs(
FileShare share,
FileSecurity fileSecurity, out
object pinningHandle)
939 pinningHandle =
null;
940 Win32Native.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES =
null;
941 if ((share &
FileShare.Inheritable) != 0 || fileSecurity !=
null)
943 sECURITY_ATTRIBUTES =
new Win32Native.SECURITY_ATTRIBUTES();
944 sECURITY_ATTRIBUTES.nLength =
Marshal.
SizeOf(sECURITY_ATTRIBUTES);
945 if ((share &
FileShare.Inheritable) != 0)
947 sECURITY_ATTRIBUTES.bInheritHandle = 1;
949 if (fileSecurity !=
null)
951 byte[] securityDescriptorBinaryForm = fileSecurity.GetSecurityDescriptorBinaryForm();
953 byte[] array = securityDescriptorBinaryForm;
954 fixed (
byte* pSecurityDescriptor = array)
956 sECURITY_ATTRIBUTES.pSecurityDescriptor = pSecurityDescriptor;
960 return sECURITY_ATTRIBUTES;
963 [SecuritySafeCritical]
964 private void VerifyHandleIsSync()
966 byte[] bytes =
new byte[1];
971 num = ReadFileNative(_handle, bytes, 0, 0,
null, out hr);
975 num = WriteFileNative(_handle, bytes, 0, 0,
null, out hr);
980 throw new ArgumentException(Environment.GetResourceString(
"Arg_HandleNotSync"));
982 __Error.WinIOError(hr,
"<OS handle>");
993 [SecuritySafeCritical]
996 if (_handle.IsClosed)
998 __Error.FileNotOpen();
1009 [SecuritySafeCritical]
1012 if (fileSecurity ==
null)
1016 if (_handle.IsClosed)
1018 __Error.FileNotOpen();
1020 fileSecurity.
Persist(_handle, _fileName);
1026 [SecuritySafeCritical]
1031 if (_handle !=
null && !_handle.IsClosed && _writePos > 0)
1033 FlushWrite(!disposing);
1038 if (_handle !=
null && !_handle.IsClosed)
1045 base.Dispose(disposing);
1050 [SecuritySafeCritical]
1053 if (_handle !=
null)
1064 Flush(flushToDisk:
false);
1070 [SecuritySafeCritical]
1071 public virtual void Flush(
bool flushToDisk)
1073 if (_handle.IsClosed)
1075 __Error.FileNotOpen();
1077 FlushInternalBuffer();
1084 private void FlushInternalBuffer()
1088 FlushWrite(calledFromFinalizer:
false);
1090 else if (_readPos < _readLen &&
CanSeek)
1096 [SecuritySafeCritical]
1097 private void FlushOSBuffer()
1099 if (!Win32Native.FlushFileBuffers(_handle))
1101 __Error.WinIOError();
1105 private void FlushRead()
1107 if (_readPos - _readLen != 0)
1109 SeekCore(_readPos - _readLen,
SeekOrigin.Current);
1115 private void FlushWrite(
bool calledFromFinalizer)
1119 IAsyncResult asyncResult = BeginWriteCore(_buffer, 0, _writePos,
null,
null);
1120 if (!calledFromFinalizer)
1127 WriteCore(_buffer, 0, _writePos);
1137 [SecuritySafeCritical]
1144 if (_handle.IsClosed)
1146 __Error.FileNotOpen();
1150 __Error.SeekNotSupported();
1154 __Error.WriteNotSupported();
1158 FlushWrite(calledFromFinalizer:
false);
1160 else if (_readPos < _readLen)
1166 if (_appendStart != -1 && value < _appendStart)
1170 SetLengthCore(value);
1173 [SecuritySafeCritical]
1174 private void SetLengthCore(
long value)
1179 VerifyOSHandlePosition();
1185 if (!Win32Native.SetEndOfFile(_handle))
1188 if (lastWin32Error == 87)
1190 throw new ArgumentOutOfRangeException(
"value", Environment.GetResourceString(
"ArgumentOutOfRange_FileLengthTooBig"));
1192 __Error.WinIOError(lastWin32Error,
string.Empty);
1221 [SecuritySafeCritical]
1222 public override int Read([In] [Out]
byte[] array,
int offset,
int count)
1236 if (array.Length - offset < count)
1240 if (_handle.IsClosed)
1242 __Error.FileNotOpen();
1245 int num = _readLen - _readPos;
1250 __Error.ReadNotSupported();
1254 FlushWrite(calledFromFinalizer:
false);
1256 if (!
CanSeek || count >= _bufferSize)
1258 num = ReadCore(array, offset, count);
1263 if (_buffer ==
null)
1265 _buffer =
new byte[_bufferSize];
1267 num = ReadCore(_buffer, 0, _bufferSize);
1272 flag = (num < _bufferSize);
1280 Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, num);
1282 if (!_isPipe && num < count && !flag)
1284 int num2 = ReadCore(array, offset + num, count - num);
1292 [SecuritySafeCritical]
1293 private int ReadCore(
byte[] buffer,
int offset,
int count)
1297 IAsyncResult asyncResult = BeginReadCore(buffer, offset, count,
null,
null, 0);
1302 VerifyOSHandlePosition();
1305 int num = ReadFileNative(_handle, buffer, offset, count,
null, out hr);
1314 throw new ArgumentException(Environment.GetResourceString(
"Arg_HandleNotSync"));
1316 __Error.WinIOError(hr,
string.Empty);
1332 [SecuritySafeCritical]
1335 if (origin < SeekOrigin.Begin || origin >
SeekOrigin.End)
1339 if (_handle.IsClosed)
1341 __Error.FileNotOpen();
1345 __Error.SeekNotSupported();
1349 FlushWrite(calledFromFinalizer:
false);
1353 offset -= _readLen - _readPos;
1357 VerifyOSHandlePosition();
1359 long num = _pos + (_readPos - _readLen);
1360 long num2 = SeekCore(offset, origin);
1361 if (_appendStart != -1 && num2 < _appendStart)
1372 Buffer.InternalBlockCopy(_buffer, _readPos, _buffer, 0, _readLen - _readPos);
1373 _readLen -= _readPos;
1381 else if (num - _readPos < num2 && num2 < num + _readLen - _readPos)
1383 int num3 = (int)(num2 - num);
1384 Buffer.InternalBlockCopy(_buffer, _readPos + num3, _buffer, 0, _readLen - (_readPos + num3));
1385 _readLen -= _readPos + num3;
1401 [SecuritySafeCritical]
1402 private long SeekCore(
long offset,
SeekOrigin origin)
1406 num = Win32Native.SetFilePointer(_handle, offset, origin, out hr);
1413 __Error.WinIOError(hr,
string.Empty);
1419 private void VerifyOSHandlePosition()
1434 throw new IOException(Environment.GetResourceString(
"IO.IO_FileStreamHandlePosition"));
1452 [SecuritySafeCritical]
1453 public override void Write(
byte[] array,
int offset,
int count)
1467 if (array.Length - offset < count)
1471 if (_handle.IsClosed)
1473 __Error.FileNotOpen();
1479 __Error.WriteNotSupported();
1481 if (_readPos < _readLen)
1490 int num = _bufferSize - _writePos;
1497 Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, num);
1508 IAsyncResult asyncResult = BeginWriteCore(_buffer, 0, _writePos,
null,
null);
1513 WriteCore(_buffer, 0, _writePos);
1517 if (count >= _bufferSize)
1519 WriteCore(array, offset, count);
1521 else if (count != 0)
1523 if (_buffer ==
null)
1525 _buffer =
new byte[_bufferSize];
1527 Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, count);
1532 [SecuritySafeCritical]
1533 private void WriteCore(
byte[] buffer,
int offset,
int count)
1537 IAsyncResult asyncResult = BeginWriteCore(buffer, offset, count,
null,
null);
1543 VerifyOSHandlePosition();
1546 int num = WriteFileNative(_handle, buffer, offset, count,
null, out hr);
1555 throw new IOException(Environment.GetResourceString(
"IO.IO_FileTooLongOrHandleNotSync"));
1557 __Error.WinIOError(hr,
string.Empty);
1577 [SecuritySafeCritical]
1578 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
1593 if (array.Length - offset < numBytes)
1597 if (_handle.IsClosed)
1599 __Error.FileNotOpen();
1603 return base.BeginRead(array, offset, numBytes, userCallback, stateObject);
1605 return BeginReadAsync(array, offset, numBytes, userCallback, stateObject);
1608 [SecuritySafeCritical]
1609 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
1610 private FileStreamAsyncResult BeginReadAsync(
byte[] array,
int offset,
int numBytes,
AsyncCallback userCallback,
object stateObject)
1614 __Error.ReadNotSupported();
1618 if (_readPos < _readLen)
1620 int num = _readLen - _readPos;
1625 Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, num);
1627 return FileStreamAsyncResult.CreateBufferedReadResult(num, userCallback, stateObject, isWrite:
false);
1629 return BeginReadCore(array, offset, numBytes, userCallback, stateObject, 0);
1633 FlushWrite(calledFromFinalizer:
false);
1635 if (_readPos == _readLen)
1637 if (numBytes < _bufferSize)
1639 if (_buffer ==
null)
1641 _buffer =
new byte[_bufferSize];
1643 IAsyncResult asyncResult = BeginReadCore(_buffer, 0, _bufferSize,
null,
null, 0);
1644 _readLen =
EndRead(asyncResult);
1645 int num2 = _readLen;
1646 if (num2 > numBytes)
1650 Buffer.InternalBlockCopy(_buffer, 0, array, offset, num2);
1652 return FileStreamAsyncResult.CreateBufferedReadResult(num2, userCallback, stateObject, isWrite:
false);
1656 return BeginReadCore(array, offset, numBytes, userCallback, stateObject, 0);
1658 int num3 = _readLen - _readPos;
1659 if (num3 > numBytes)
1663 Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, num3);
1665 if (num3 >= numBytes)
1667 return FileStreamAsyncResult.CreateBufferedReadResult(num3, userCallback, stateObject, isWrite:
false);
1671 return BeginReadCore(array, offset + num3, numBytes - num3, userCallback, stateObject, num3);
1674 [SecuritySafeCritical]
1675 private unsafe FileStreamAsyncResult BeginReadCore(
byte[] bytes,
int offset,
int numBytes,
AsyncCallback userCallback,
object stateObject,
int numBufferedBytesRead)
1677 FileStreamAsyncResult fileStreamAsyncResult =
new FileStreamAsyncResult(numBufferedBytesRead, bytes, _handle, userCallback, stateObject, isWrite:
false);
1684 VerifyOSHandlePosition();
1686 if (_pos + numBytes > length)
1688 numBytes = (int)((_pos <= length) ? (length - _pos) : 0);
1694 if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(
EventLevel.Informational, (
EventKeywords)16L))
1696 FrameworkEventSource.Log.ThreadTransferSend((
long)fileStreamAsyncResult.OverLapped, 2,
string.Empty, multiDequeues:
false);
1699 int num = ReadFileNative(_handle, bytes, offset, numBytes, overLapped, out hr);
1700 if (num == -1 && numBytes != -1)
1706 fileStreamAsyncResult.CallUserCallback();
1709 if (!_handle.IsClosed &&
CanSeek)
1715 __Error.EndOfFile();
1719 __Error.WinIOError(hr,
string.Empty);
1726 return fileStreamAsyncResult;
1738 [SecuritySafeCritical]
1741 if (asyncResult ==
null)
1747 return base.EndRead(asyncResult);
1749 FileStreamAsyncResult fileStreamAsyncResult = asyncResult as FileStreamAsyncResult;
1750 if (fileStreamAsyncResult ==
null || fileStreamAsyncResult.IsWrite)
1752 __Error.WrongAsyncResult();
1756 __Error.EndReadCalledTwice();
1758 fileStreamAsyncResult.Wait();
1759 fileStreamAsyncResult.ReleaseNativeResource();
1760 if (fileStreamAsyncResult.ErrorCode != 0)
1762 __Error.WinIOError(fileStreamAsyncResult.ErrorCode,
string.Empty);
1764 return fileStreamAsyncResult.NumBytesRead;
1771 [SecuritySafeCritical]
1774 if (_handle.IsClosed)
1776 __Error.FileNotOpen();
1778 if (_readLen == 0 && !
CanRead)
1780 __Error.ReadNotSupported();
1782 if (_readPos == _readLen)
1786 FlushWrite(calledFromFinalizer:
false);
1788 if (_buffer ==
null)
1790 _buffer =
new byte[_bufferSize];
1792 _readLen = ReadCore(_buffer, 0, _bufferSize);
1795 if (_readPos == _readLen)
1799 int result = _buffer[_readPos];
1820 [SecuritySafeCritical]
1821 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
1836 if (array.Length - offset < numBytes)
1840 if (_handle.IsClosed)
1842 __Error.FileNotOpen();
1846 return base.BeginWrite(array, offset, numBytes, userCallback, stateObject);
1848 return BeginWriteAsync(array, offset, numBytes, userCallback, stateObject);
1851 [SecuritySafeCritical]
1852 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
1853 private FileStreamAsyncResult BeginWriteAsync(
byte[] array,
int offset,
int numBytes,
AsyncCallback userCallback,
object stateObject)
1857 __Error.WriteNotSupported();
1863 FlushWrite(calledFromFinalizer:
false);
1865 return BeginWriteCore(array, offset, numBytes, userCallback, stateObject);
1869 if (_readPos < _readLen)
1876 int num = _bufferSize - _writePos;
1877 if (numBytes <= num)
1881 _buffer =
new byte[_bufferSize];
1883 Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, numBytes);
1884 _writePos += numBytes;
1885 return FileStreamAsyncResult.CreateBufferedReadResult(numBytes, userCallback, stateObject, isWrite:
true);
1889 FlushWrite(calledFromFinalizer:
false);
1891 return BeginWriteCore(array, offset, numBytes, userCallback, stateObject);
1894 [SecuritySafeCritical]
1895 private unsafe FileStreamAsyncResult BeginWriteCore(
byte[] bytes,
int offset,
int numBytes,
AsyncCallback userCallback,
object stateObject)
1897 FileStreamAsyncResult fileStreamAsyncResult =
new FileStreamAsyncResult(0, bytes, _handle, userCallback, stateObject, isWrite:
true);
1904 VerifyOSHandlePosition();
1906 if (_pos + numBytes > length)
1908 SetLengthCore(_pos + numBytes);
1914 if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(
EventLevel.Informational, (
EventKeywords)16L))
1916 FrameworkEventSource.Log.ThreadTransferSend((
long)fileStreamAsyncResult.OverLapped, 2,
string.Empty, multiDequeues:
false);
1919 int num = WriteFileNative(_handle, bytes, offset, numBytes, overLapped, out hr);
1920 if (num == -1 && numBytes != -1)
1925 fileStreamAsyncResult.CallUserCallback();
1928 if (!_handle.IsClosed &&
CanSeek)
1934 __Error.EndOfFile();
1938 __Error.WinIOError(hr,
string.Empty);
1945 return fileStreamAsyncResult;
1956 [SecuritySafeCritical]
1959 if (asyncResult ==
null)
1965 base.EndWrite(asyncResult);
1968 FileStreamAsyncResult fileStreamAsyncResult = asyncResult as FileStreamAsyncResult;
1969 if (fileStreamAsyncResult ==
null || !fileStreamAsyncResult.IsWrite)
1971 __Error.WrongAsyncResult();
1975 __Error.EndWriteCalledTwice();
1977 fileStreamAsyncResult.Wait();
1978 fileStreamAsyncResult.ReleaseNativeResource();
1979 if (fileStreamAsyncResult.ErrorCode != 0)
1981 __Error.WinIOError(fileStreamAsyncResult.ErrorCode,
string.Empty);
1989 [SecuritySafeCritical]
1992 if (_handle.IsClosed)
1994 __Error.FileNotOpen();
2000 __Error.WriteNotSupported();
2002 if (_readPos < _readLen)
2008 if (_buffer ==
null)
2010 _buffer =
new byte[_bufferSize];
2013 if (_writePos == _bufferSize)
2015 FlushWrite(calledFromFinalizer:
false);
2017 _buffer[_writePos] = value;
2028 [SecuritySafeCritical]
2029 public virtual void Lock(
long position,
long length)
2031 if (position < 0 || length < 0)
2035 if (_handle.IsClosed)
2037 __Error.FileNotOpen();
2039 int offsetLow = (int)position;
2040 int offsetHigh = (int)(position >> 32);
2041 int countLow = (int)length;
2042 int countHigh = (int)(length >> 32);
2043 if (!Win32Native.LockFile(_handle, offsetLow, offsetHigh, countLow, countHigh))
2045 __Error.WinIOError();
2054 [SecuritySafeCritical]
2055 public virtual void Unlock(
long position,
long length)
2057 if (position < 0 || length < 0)
2061 if (_handle.IsClosed)
2063 __Error.FileNotOpen();
2065 int offsetLow = (int)position;
2066 int offsetHigh = (int)(position >> 32);
2067 int countLow = (int)length;
2068 int countHigh = (int)(length >> 32);
2069 if (!Win32Native.UnlockFile(_handle, offsetLow, offsetHigh, countLow, countHigh))
2071 __Error.WinIOError();
2078 if (bytes.Length - offset < count)
2082 if (bytes.Length == 0)
2088 int numBytesRead = 0;
2089 fixed (
byte* ptr = bytes)
2091 num = ((!_isAsync) ? Win32Native.ReadFile(handle, ptr + offset, count, out numBytesRead, IntPtr.Zero) : Win32Native.ReadFile(handle, ptr + offset, count, IntPtr.Zero, overlapped));
2096 if (hr == 109 || hr == 233)
2107 return numBytesRead;
2113 if (bytes.Length - offset < count)
2115 throw new IndexOutOfRangeException(Environment.GetResourceString(
"IndexOutOfRange_IORaceCondition"));
2117 if (bytes.Length == 0)
2122 int numBytesWritten = 0;
2124 fixed (
byte* ptr = bytes)
2126 num = ((!_isAsync) ? Win32Native.WriteFile(handle, ptr + offset, count, out numBytesWritten, IntPtr.Zero) : Win32Native.WriteFile(handle, ptr + offset, count, IntPtr.Zero, overlapped));
2142 return numBytesWritten;
2160 [SecuritySafeCritical]
2161 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
2176 if (buffer.Length - offset < count)
2182 return base.ReadAsync(buffer, offset, count, cancellationToken);
2186 return Task.FromCancellation<
int>(cancellationToken);
2188 if (_handle.IsClosed)
2190 __Error.FileNotOpen();
2194 return base.ReadAsync(buffer, offset, count, cancellationToken);
2196 FileStreamReadWriteTask<int> fileStreamReadWriteTask =
new FileStreamReadWriteTask<int>(cancellationToken);
2198 fileStreamReadWriteTask._asyncResult = BeginReadAsync(buffer, offset, count, userCallback, fileStreamReadWriteTask);
2199 if (fileStreamReadWriteTask._asyncResult.IsAsync && cancellationToken.
CanBeCanceled)
2201 Action<object> callback =
FileStream.CancelTask<
int>;
2202 fileStreamReadWriteTask._registration = cancellationToken.
Register(callback, fileStreamReadWriteTask);
2203 if (fileStreamReadWriteTask._asyncResult.IsCompleted)
2205 fileStreamReadWriteTask._registration.Dispose();
2208 return fileStreamReadWriteTask;
2226 [SecuritySafeCritical]
2227 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
2242 if (buffer.Length - offset < count)
2248 return base.WriteAsync(buffer, offset, count, cancellationToken);
2252 return Task.FromCancellation(cancellationToken);
2254 if (_handle.IsClosed)
2256 __Error.FileNotOpen();
2260 return base.WriteAsync(buffer, offset, count, cancellationToken);
2262 FileStreamReadWriteTask<VoidTaskResult> fileStreamReadWriteTask =
new FileStreamReadWriteTask<VoidTaskResult>(cancellationToken);
2264 fileStreamReadWriteTask._asyncResult = BeginWriteAsync(buffer, offset, count, userCallback, fileStreamReadWriteTask);
2265 if (fileStreamReadWriteTask._asyncResult.IsAsync && cancellationToken.
CanBeCanceled)
2267 Action<object> callback =
FileStream.CancelTask<VoidTaskResult>;
2268 fileStreamReadWriteTask._registration = cancellationToken.
Register(callback, fileStreamReadWriteTask);
2269 if (fileStreamReadWriteTask._asyncResult.IsCompleted)
2271 fileStreamReadWriteTask._registration.Dispose();
2274 return fileStreamReadWriteTask;
2277 [SecuritySafeCritical]
2278 private static void CancelTask<T>(
object state)
2280 FileStreamReadWriteTask<T> fileStreamReadWriteTask = state as FileStreamReadWriteTask<T>;
2281 FileStreamAsyncResult asyncResult = fileStreamReadWriteTask._asyncResult;
2284 if (!asyncResult.IsCompleted)
2286 asyncResult.Cancel();
2289 catch (Exception exceptionObject)
2291 fileStreamReadWriteTask.TrySetException(exceptionObject);
2295 [SecuritySafeCritical]
2296 private static void EndReadTask(IAsyncResult iar)
2298 FileStreamAsyncResult fileStreamAsyncResult = iar as FileStreamAsyncResult;
2299 FileStreamReadWriteTask<int> fileStreamReadWriteTask = fileStreamAsyncResult.AsyncState as FileStreamReadWriteTask<int>;
2302 if (fileStreamAsyncResult.IsAsync)
2304 fileStreamAsyncResult.ReleaseNativeResource();
2305 fileStreamReadWriteTask._registration.Dispose();
2307 if (fileStreamAsyncResult.ErrorCode == 995)
2309 CancellationToken cancellationToken = fileStreamReadWriteTask._cancellationToken;
2310 fileStreamReadWriteTask.TrySetCanceled(cancellationToken);
2314 fileStreamReadWriteTask.TrySetResult(fileStreamAsyncResult.NumBytesRead);
2317 catch (Exception exceptionObject)
2319 fileStreamReadWriteTask.TrySetException(exceptionObject);
2323 [SecuritySafeCritical]
2324 private static void EndWriteTask(IAsyncResult iar)
2326 FileStreamAsyncResult fileStreamAsyncResult = iar as FileStreamAsyncResult;
2327 FileStreamReadWriteTask<VoidTaskResult> fileStreamReadWriteTask = iar.AsyncState as FileStreamReadWriteTask<VoidTaskResult>;
2330 if (fileStreamAsyncResult.IsAsync)
2332 fileStreamAsyncResult.ReleaseNativeResource();
2333 fileStreamReadWriteTask._registration.Dispose();
2335 if (fileStreamAsyncResult.ErrorCode == 995)
2337 CancellationToken cancellationToken = fileStreamReadWriteTask._cancellationToken;
2338 fileStreamReadWriteTask.TrySetCanceled(cancellationToken);
2342 fileStreamReadWriteTask.TrySetResult(
default(VoidTaskResult));
2345 catch (Exception exceptionObject)
2347 fileStreamReadWriteTask.TrySetException(exceptionObject);
2356 [SecuritySafeCritical]
2357 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
2362 return base.FlushAsync(cancellationToken);
2366 return Task.FromCancellation(cancellationToken);
2368 if (_handle.IsClosed)
2370 __Error.FileNotOpen();
2374 FlushInternalBuffer();
2382 return Task.
Factory.StartNew(delegate(
object state)
FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
static new TaskFactory< TResult > Factory
Provides access to factory methods for creating and configuring T:System.Threading....
FileSystemRights
Defines the access rights to use when creating access and audit rules.
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
Describes a set of security permissions applied to code. This class cannot be inherited.
FileIOPermissionAccess
Specifies the type of file access requested.
FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
Propagates notification that operations should be canceled.
string Name
Gets the name of the FileStream that was passed to the constructor.
FileOptions
Represents advanced options for creating a T:System.IO.FileStream object.
virtual void Unlock(long position, long length)
Allows access by other processes to all or part of a file that was previously locked.
FileStream(SafeFileHandle handle, FileAccess access, int bufferSize)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
FileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options)
Initializes a new instance of the T:System.IO.FileStream class with the specified path,...
override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
Begins an asynchronous read operation. (Consider using M:System.IO.FileStream.ReadAsync(System....
StringComparison
Specifies the culture, case, and sort rules to be used by certain overloads of the M:System....
EventKeywords
Defines the standard keywords that apply to events.
FileMode
Specifies how the operating system should open a file.
Represents the access control and audit security for a file. This class cannot be inherited.
Represents an object that handles the low-level work of queuing tasks onto threads.
IntPtr InternalLow
Specifies a system-dependent status. Reserved for operating system use.
The exception that is thrown when the value of an argument is outside the allowable range of values a...
Represents a callback delegate that has been registered with a T:System.Threading....
static int SizeOf(object structure)
Returns the unmanaged size of an object in bytes.
delegate void AsyncCallback(IAsyncResult ar)
References a method to be called when a corresponding asynchronous operation completes.
override void Write(byte[] array, int offset, int count)
Writes a block of bytes to the file stream.
override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
Asynchronously writes a sequence of bytes to the current stream, advances the current position within...
bool CanBeCanceled
Gets whether this token is capable of being in the canceled state.
Serves as the base class for application-defined exceptions.
FileSecurity GetAccessControl()
Gets a T:System.Security.AccessControl.FileSecurity object that encapsulates the access control list ...
override void Dispose(bool disposing)
Releases the unmanaged resources used by the T:System.IO.FileStream and optionally releases the manag...
FileStream(SafeFileHandle handle, FileAccess access)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
override int Read([In] [Out] byte[] array, int offset, int count)
Reads a block of bytes from the stream and writes the data in a given buffer.
static string GetFileName(string path)
Returns the file name and extension of the specified path string.
bool IsCancellationRequested
Gets whether cancellation has been requested for this token.
SeekOrigin
Specifies the position in a stream to use for seeking.
override bool CanWrite
Gets a value indicating whether the current stream supports writing.
TaskCreationOptions
Specifies flags that control optional behavior for the creation and execution of tasks.
FileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity)
Initializes a new instance of the T:System.IO.FileStream class with the specified path,...
override long Position
Gets or sets the current position of this stream.
EventLevel
Identifies the level of an event.
static TaskScheduler Default
Gets the default T:System.Threading.Tasks.TaskScheduler instance that is provided by the ....
FileStream(IntPtr handle, FileAccess access, bool ownsHandle)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
SecurityAction
Specifies the security actions that can be performed using declarative security.
Provides information about, and means to manipulate, the current environment and platform....
Represents the status of an asynchronous operation.
sealed override void Persist(string name, AccessControlSections includeSections)
Saves the specified sections of the security descriptor associated with this T:System....
The exception that is thrown when an attempt is made to access an element of an array or collection w...
override bool CanSeek
Gets a value indicating whether the current stream supports seeking.
override void WriteByte(byte value)
Writes a byte to the current position in the file stream.
int OffsetLow
Specifies a file position at which to start the transfer.
FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
Initializes a new instance of the T:System.IO.FileStream class with the specified path,...
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
FileStream(string path, FileMode mode, FileAccess access)
Initializes a new instance of the T:System.IO.FileStream class with the specified path,...
Opens the file if it exists and seeks to the end of the file, or creates a new file....
static Task FromException(Exception exception)
Creates a T:System.Threading.Tasks.Task that has completed with a specified exception.
The exception that is thrown when an I/O error occurs.
FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
override Task< int > ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
Asynchronously reads a sequence of bytes from the current stream, advances the position within the st...
Defines the underlying structure of all code access permissions.
A platform-specific type that is used to represent a pointer or a handle.
override void EndWrite(IAsyncResult asyncResult)
Ends an asynchronous write operation and blocks until the I/O operation is complete....
override bool CanRead
Gets a value indicating whether the current stream supports reading.
static GCHandle Alloc(object value)
Allocates a F:System.Runtime.InteropServices.GCHandleType.Normal handle for the specified object.
virtual void Lock(long position, long length)
Prevents other processes from reading from or writing to the T:System.IO.FileStream.
Indicates that no additional options should be used when creating a T:System.IO.FileStream object.
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
GCHandleType
Represents the types of handles the T:System.Runtime.InteropServices.GCHandle class can allocate.
Indicates that a file can be used for asynchronous reading and writing.
Provides a way to access a managed object from unmanaged memory.
static Task CompletedTask
Gets a task that has already completed successfully.
override int ReadByte()
Reads a byte from the file and advances the read position one byte.
static void RevertAssert()
Causes any previous M:System.Security.CodeAccessPermission.Assert for the current frame to be removed...
override void Flush()
Clears buffers for this stream and causes any buffered data to be written to the file.
AccessControlActions
Specifies the actions that are permitted for securable objects.
Read and write access to the file. Data can be written to and read from the file.
The exception that is thrown when one of the arguments provided to a method is not valid.
override long Length
Gets the length in bytes of the stream.
override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
Begins an asynchronous write operation. (Consider using M:System.IO.FileStream.WriteAsync(System....
static bool BindHandle(IntPtr osHandle)
Binds an operating system handle to the T:System.Threading.ThreadPool.
virtual SafeFileHandle SafeFileHandle
Gets a T:Microsoft.Win32.SafeHandles.SafeFileHandle object that represents the operating system file ...
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
FileAccess
Defines constants for read, write, or read/write access to a file.
static readonly IntPtr Zero
A read-only field that represents a pointer or handle that has been initialized to zero.
override Task FlushAsync(CancellationToken cancellationToken)
Asynchronously clears all buffers for this stream, causes any buffered data to be written to the unde...
void Dispose()
Releases all resources used by the T:System.IO.Stream.
Manipulates arrays of primitive types.
FileStream(IntPtr handle, FileAccess access)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
Initializes a new instance of the T:System.IO.FileStream class with the specified path,...
virtual bool IsAsync
Gets a value indicating whether the FileStream was opened asynchronously or synchronously.
void SetAccessControl(FileSecurity fileSecurity)
Applies access control list (ACL) entries described by a T:System.Security.AccessControl....
void Assert()
Declares that the calling code can access the resource protected by a permission demand through the c...
int OffsetHigh
Specifies the high word of the byte offset at which to start the transfer.
Controls the ability to access files and folders. This class cannot be inherited.
override long Seek(long offset, SeekOrigin origin)
Sets the current position of this stream to the given value.
virtual void Flush(bool flushToDisk)
Clears buffers for this stream and causes any buffered data to be written to the file,...
static int GetLastWin32Error()
Returns the error code returned by the last unmanaged function that was called using platform invoke ...
SecurityPermissionFlag
Specifies access flags for the security permission object.
AccessControlSections
Specifies which sections of a security descriptor to save or load.
Provides atomic operations for variables that are shared by multiple threads.
The P:System.Uri.LocalPath data.
The exception that is thrown when a security error is detected.
virtual IntPtr Handle
Gets the operating system file handle for the file that the current FileStream object encapsulates.
Performs operations on T:System.String instances that contain file or directory path information....
CancellationTokenRegistration Register(Action callback)
Registers a delegate that will be called when this T:System.Threading.CancellationToken is canceled.
Provides an explicit layout that is visible from unmanaged code and that will have the same layout as...
override void SetLength(long value)
Sets the length of this stream to the given value.
FileStream(string path, FileMode mode, FileAccess access, FileShare share)
Initializes a new instance of the T:System.IO.FileStream class with the specified path,...
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I...
FileShare
Contains constants for controlling the kind of access other T:System.IO.FileStream objects can have t...
override int EndRead(IAsyncResult asyncResult)
Waits for the pending asynchronous read operation to complete. (Consider using M:System....
Represents an asynchronous operation that can return a value.
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....