mscorlib(4.0.0.0) API with additions
FileStream.cs
1 using Microsoft.Win32;
2 using Microsoft.Win32.SafeHandles;
5 using System.Security;
8 using System.Threading;
10 
11 namespace System.IO
12 {
14  [ComVisible(true)]
15  public class FileStream : Stream
16  {
17  private sealed class FileStreamReadWriteTask<T> : Task<T>
18  {
19  internal CancellationToken _cancellationToken;
20 
21  internal CancellationTokenRegistration _registration;
22 
23  internal FileStreamAsyncResult _asyncResult;
24 
25  internal FileStreamReadWriteTask(CancellationToken cancellationToken)
26  {
27  _cancellationToken = cancellationToken;
28  }
29  }
30 
31  internal const int DefaultBufferSize = 4096;
32 
33  private const bool _canUseAsync = true;
34 
35  private byte[] _buffer;
36 
37  private string _fileName;
38 
39  private bool _isAsync;
40 
41  private bool _canRead;
42 
43  private bool _canWrite;
44 
45  private bool _canSeek;
46 
47  private bool _exposedHandle;
48 
49  private bool _isPipe;
50 
51  private int _readPos;
52 
53  private int _readLen;
54 
55  private int _writePos;
56 
57  private int _bufferSize;
58 
59  [SecurityCritical]
60  private SafeFileHandle _handle;
61 
62  private long _pos;
63 
64  private long _appendStart;
65 
66  private static AsyncCallback s_endReadTask;
67 
68  private static AsyncCallback s_endWriteTask;
69 
70  private static Action<object> s_cancelReadHandler;
71 
72  private static Action<object> s_cancelWriteHandler;
73 
74  private const int FILE_ATTRIBUTE_NORMAL = 128;
75 
76  private const int FILE_ATTRIBUTE_ENCRYPTED = 16384;
77 
78  private const int FILE_FLAG_OVERLAPPED = 1073741824;
79 
80  internal const int GENERIC_READ = int.MinValue;
81 
82  private const int GENERIC_WRITE = 1073741824;
83 
84  private const int FILE_BEGIN = 0;
85 
86  private const int FILE_CURRENT = 1;
87 
88  private const int FILE_END = 2;
89 
90  internal const int ERROR_BROKEN_PIPE = 109;
91 
92  internal const int ERROR_NO_DATA = 232;
93 
94  private const int ERROR_HANDLE_EOF = 38;
95 
96  private const int ERROR_INVALID_PARAMETER = 87;
97 
98  private const int ERROR_IO_PENDING = 997;
99 
103  public override bool CanRead => _canRead;
104 
108  public override bool CanWrite => _canWrite;
109 
113  public override bool CanSeek => _canSeek;
114 
118  public virtual bool IsAsync => _isAsync;
119 
125  public override long Length
126  {
127  [SecuritySafeCritical]
128  get
129  {
130  if (_handle.IsClosed)
131  {
132  __Error.FileNotOpen();
133  }
134  if (!CanSeek)
135  {
136  __Error.SeekNotSupported();
137  }
138  int highSize = 0;
139  int num = 0;
140  num = Win32Native.GetFileSize(_handle, out highSize);
141  if (num == -1)
142  {
143  int lastWin32Error = Marshal.GetLastWin32Error();
144  if (lastWin32Error != 0)
145  {
146  __Error.WinIOError(lastWin32Error, string.Empty);
147  }
148  }
149  long num2 = ((long)highSize << 32) | (uint)num;
150  if (_writePos > 0 && _pos + _writePos > num2)
151  {
152  num2 = _writePos + _pos;
153  }
154  return num2;
155  }
156  }
157 
160  public string Name
161  {
162  [SecuritySafeCritical]
163  get
164  {
165  if (_fileName == null)
166  {
167  return Environment.GetResourceString("IO_UnknownFileName");
168  }
169  FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, _fileName, checkForDuplicates: false, needFullPath: false);
170  return _fileName;
171  }
172  }
173 
174  internal string NameInternal
175  {
176  get
177  {
178  if (_fileName == null)
179  {
180  return "<UnknownFileName>";
181  }
182  return _fileName;
183  }
184  }
185 
192  public override long Position
193  {
194  [SecuritySafeCritical]
195  get
196  {
197  if (_handle.IsClosed)
198  {
199  __Error.FileNotOpen();
200  }
201  if (!CanSeek)
202  {
203  __Error.SeekNotSupported();
204  }
205  if (_exposedHandle)
206  {
207  VerifyOSHandlePosition();
208  }
209  return _pos + (_readPos - _readLen + _writePos);
210  }
211  set
212  {
213  if (value < 0)
214  {
215  throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
216  }
217  if (_writePos > 0)
218  {
219  FlushWrite(calledFromFinalizer: false);
220  }
221  _readPos = 0;
222  _readLen = 0;
223  Seek(value, SeekOrigin.Begin);
224  }
225  }
226 
230  [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
231  public virtual IntPtr Handle
232  {
233  [SecurityCritical]
234  [SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
235  get
236  {
237  Flush();
238  _readPos = 0;
239  _readLen = 0;
240  _writePos = 0;
241  _exposedHandle = true;
242  return _handle.DangerousGetHandle();
243  }
244  }
245 
248  public virtual SafeFileHandle SafeFileHandle
249  {
250  [SecurityCritical]
251  [SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
252  get
253  {
254  Flush();
255  _readPos = 0;
256  _readLen = 0;
257  _writePos = 0;
258  _exposedHandle = true;
259  return _handle;
260  }
261  }
262 
263  internal FileStream()
264  {
265  }
266 
284  [SecuritySafeCritical]
285  public FileStream(string path, FileMode mode)
286  : this(path, mode, (mode == FileMode.Append) ? FileAccess.Write : FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.None, Path.GetFileName(path), bFromProxy: false)
287  {
288  }
289 
309  [SecuritySafeCritical]
310  public FileStream(string path, FileMode mode, FileAccess access)
311  : this(path, mode, access, FileShare.Read, 4096, FileOptions.None, Path.GetFileName(path), bFromProxy: false)
312  {
313  }
314 
335  [SecuritySafeCritical]
336  public FileStream(string path, FileMode mode, FileAccess access, FileShare share)
337  : this(path, mode, access, share, 4096, FileOptions.None, Path.GetFileName(path), bFromProxy: false)
338  {
339  }
340 
363  [SecuritySafeCritical]
364  public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
365  : this(path, mode, access, share, bufferSize, FileOptions.None, Path.GetFileName(path), bFromProxy: false)
366  {
367  }
368 
393  [SecuritySafeCritical]
394  public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
395  : this(path, mode, access, share, bufferSize, options, Path.GetFileName(path), bFromProxy: false)
396  {
397  }
398 
422  [SecuritySafeCritical]
423  public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
424  : this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None, Path.GetFileName(path), bFromProxy: false)
425  {
426  }
427 
454  [SecuritySafeCritical]
455  public FileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity)
456  {
457  object pinningHandle;
458  Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share, fileSecurity, out pinningHandle);
459  try
460  {
461  Init(path, mode, (FileAccess)0, (int)rights, useRights: true, share, bufferSize, options, secAttrs, Path.GetFileName(path), bFromProxy: false, useLongPath: false, checkHost: false);
462  }
463  finally
464  {
465  if (pinningHandle != null)
466  {
467  ((GCHandle)pinningHandle).Free();
468  }
469  }
470  }
471 
497  [SecuritySafeCritical]
498  public FileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options)
499  {
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);
502  }
503 
504  [SecurityCritical]
505  internal FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy)
506  {
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);
509  }
510 
511  [SecurityCritical]
512  internal FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath)
513  {
514  Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
515  Init(path, mode, access, 0, useRights: false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, useLongPath, checkHost: false);
516  }
517 
518  [SecurityCritical]
519  internal FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath, bool checkHost)
520  {
521  Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
522  Init(path, mode, access, 0, useRights: false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, useLongPath, checkHost);
523  }
524 
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)
527  {
528  if (path == null)
529  {
530  throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
531  }
532  if (path.Length == 0)
533  {
534  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
535  }
536  _fileName = msgPath;
537  _exposedHandle = false;
538  FileShare fileShare = share & ~FileShare.Inheritable;
539  string text = null;
540  if (mode < FileMode.CreateNew || mode > FileMode.Append)
541  {
542  text = "mode";
543  }
544  else if (!useRights && (access < FileAccess.Read || access > FileAccess.ReadWrite))
545  {
546  text = "access";
547  }
548  else if (useRights && (rights < 1 || rights > 2032127))
549  {
550  text = "rights";
551  }
552  else if (fileShare < FileShare.None || fileShare > (FileShare.Read | FileShare.Write | FileShare.Delete))
553  {
554  text = "share";
555  }
556  if (text != null)
557  {
558  throw new ArgumentOutOfRangeException(text, Environment.GetResourceString("ArgumentOutOfRange_Enum"));
559  }
560  if (options != 0 && (options & (FileOptions)67092479) != 0)
561  {
562  throw new ArgumentOutOfRangeException("options", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
563  }
564  if (bufferSize <= 0)
565  {
566  throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
567  }
568  if (((!useRights && (access & FileAccess.Write) == (FileAccess)0) || (useRights && (rights & 0x116) == 0)) && (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append))
569  {
570  if (!useRights)
571  {
572  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo", mode, access));
573  }
574  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&RightsCombo", mode, (FileSystemRights)rights));
575  }
576  if (useRights && mode == FileMode.Truncate)
577  {
578  if (rights != 278)
579  {
580  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileModeTruncate&RightsCombo", mode, (FileSystemRights)rights));
581  }
582  useRights = false;
583  access = FileAccess.Write;
584  }
585  int dwDesiredAccess;
586  if (!useRights)
587  {
588  int num;
589  switch (access)
590  {
591  default:
592  num = -1073741824;
593  break;
594  case FileAccess.Write:
595  num = 1073741824;
596  break;
597  case FileAccess.Read:
598  num = int.MinValue;
599  break;
600  }
601  dwDesiredAccess = num;
602  }
603  else
604  {
605  dwDesiredAccess = rights;
606  }
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))
610  {
611  throw new ArgumentException(Environment.GetResourceString("Arg_DevicesNotSupported"));
612  }
613  bool flag = false;
614  if ((!useRights && (access & FileAccess.Read) != 0) || (useRights && (rights & 0x200A9) != 0))
615  {
616  if (mode == FileMode.Append)
617  {
618  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidAppendMode"));
619  }
620  flag = true;
621  }
622  if (CodeAccessSecurityEngine.QuickCheckForAllDemands())
623  {
624  FileIOPermission.EmulateFileIOPermissionChecks(text2);
625  }
626  else
627  {
628  FileIOPermissionAccess fileIOPermissionAccess = FileIOPermissionAccess.NoAccess;
629  if (flag)
630  {
631  fileIOPermissionAccess |= FileIOPermissionAccess.Read;
632  }
633  if ((!useRights && (access & FileAccess.Write) != 0) || (useRights && (rights & 0xD0156) != 0) || (useRights && (rights & 0x100000) != 0 && mode == FileMode.OpenOrCreate))
634  {
635  fileIOPermissionAccess = ((mode != FileMode.Append) ? (fileIOPermissionAccess | FileIOPermissionAccess.Write) : (fileIOPermissionAccess | FileIOPermissionAccess.Append));
636  }
637  AccessControlActions control = (secAttrs != null && secAttrs.pSecurityDescriptor != null) ? AccessControlActions.Change : AccessControlActions.None;
638  FileIOPermission.QuickDemand(fileIOPermissionAccess, control, new string[1]
639  {
640  text2
641  }, checkForDuplicates: false, needFullPath: false);
642  }
643  share &= ~FileShare.Inheritable;
644  bool flag2 = mode == FileMode.Append;
645  if (mode == FileMode.Append)
646  {
647  mode = FileMode.OpenOrCreate;
648  }
649  if ((options & FileOptions.Asynchronous) != 0)
650  {
651  _isAsync = true;
652  }
653  else
654  {
655  options &= ~FileOptions.Asynchronous;
656  }
657  int num2 = (int)options;
658  num2 |= 0x100000;
659  int errorMode = Win32Native.SetErrorMode(1);
660  try
661  {
662  string text3 = text2;
663  if (useLongPath)
664  {
665  text3 = Path.AddLongPathPrefix(text3);
666  }
667  _handle = Win32Native.SafeCreateFile(text3, dwDesiredAccess, share, secAttrs, mode, num2, IntPtr.Zero);
668  if (_handle.IsInvalid)
669  {
670  int num3 = Marshal.GetLastWin32Error();
671  if (num3 == 3 && text2.Equals(Directory.InternalGetDirectoryRoot(text2)))
672  {
673  num3 = 5;
674  }
675  bool flag3 = false;
676  if (!bFromProxy)
677  {
678  try
679  {
680  FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, _fileName, checkForDuplicates: false, needFullPath: false);
681  flag3 = true;
682  }
683  catch (SecurityException)
684  {
685  }
686  }
687  if (flag3)
688  {
689  __Error.WinIOError(num3, _fileName);
690  }
691  else
692  {
693  __Error.WinIOError(num3, msgPath);
694  }
695  }
696  }
697  finally
698  {
699  Win32Native.SetErrorMode(errorMode);
700  }
701  int fileType = Win32Native.GetFileType(_handle);
702  if (fileType != 1)
703  {
704  _handle.Close();
705  throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
706  }
707  if (_isAsync)
708  {
709  bool flag4 = false;
710  new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
711  try
712  {
713  flag4 = ThreadPool.BindHandle(_handle);
714  }
715  finally
716  {
718  if (!flag4)
719  {
720  _handle.Close();
721  }
722  }
723  if (!flag4)
724  {
725  throw new IOException(Environment.GetResourceString("IO.IO_BindHandleFailed"));
726  }
727  }
728  if (!useRights)
729  {
730  _canRead = ((access & FileAccess.Read) != (FileAccess)0);
731  _canWrite = ((access & FileAccess.Write) != (FileAccess)0);
732  }
733  else
734  {
735  _canRead = ((rights & 1) != 0);
736  _canWrite = ((rights & 2) != 0 || (rights & 4) != 0);
737  }
738  _canSeek = true;
739  _isPipe = false;
740  _pos = 0L;
741  _bufferSize = bufferSize;
742  _readPos = 0;
743  _readLen = 0;
744  _writePos = 0;
745  if (flag2)
746  {
747  _appendStart = SeekCore(0L, SeekOrigin.End);
748  }
749  else
750  {
751  _appendStart = -1L;
752  }
753  }
754 
763  [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
764  public FileStream(IntPtr handle, FileAccess access)
765  : this(handle, access, ownsHandle: true, 4096, isAsync: false)
766  {
767  }
768 
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")]
780  public FileStream(IntPtr handle, FileAccess access, bool ownsHandle)
781  : this(handle, access, ownsHandle, 4096, isAsync: false)
782  {
783  }
784 
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")]
797  public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
798  : this(handle, access, ownsHandle, bufferSize, isAsync: false)
799  {
800  }
801 
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")]
818  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
819  public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
820  : this(new SafeFileHandle(handle, ownsHandle), access, bufferSize, isAsync)
821  {
822  }
823 
832  [SecuritySafeCritical]
833  public FileStream(SafeFileHandle handle, FileAccess access)
834  : this(handle, access, 4096, isAsync: false)
835  {
836  }
837 
847  [SecuritySafeCritical]
848  public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize)
849  : this(handle, access, bufferSize, isAsync: false)
850  {
851  }
852 
864  [SecuritySafeCritical]
865  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
866  public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
867  {
868  if (handle.IsInvalid)
869  {
870  throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
871  }
872  _handle = handle;
873  _exposedHandle = true;
874  if (access < FileAccess.Read || access > FileAccess.ReadWrite)
875  {
876  throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
877  }
878  if (bufferSize <= 0)
879  {
880  throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
881  }
882  int fileType = Win32Native.GetFileType(_handle);
883  _isAsync = isAsync;
884  _canRead = ((access & FileAccess.Read) != (FileAccess)0);
885  _canWrite = ((access & FileAccess.Write) != (FileAccess)0);
886  _canSeek = (fileType == 1);
887  _bufferSize = bufferSize;
888  _readPos = 0;
889  _readLen = 0;
890  _writePos = 0;
891  _fileName = null;
892  _isPipe = (fileType == 3);
893  if (_isAsync)
894  {
895  bool flag = false;
896  try
897  {
898  flag = ThreadPool.BindHandle(_handle);
899  }
900  catch (ApplicationException)
901  {
902  throw new ArgumentException(Environment.GetResourceString("Arg_HandleNotAsync"));
903  }
904  if (!flag)
905  {
906  throw new IOException(Environment.GetResourceString("IO.IO_BindHandleFailed"));
907  }
908  }
909  else if (fileType != 3)
910  {
911  VerifyHandleIsSync();
912  }
913  if (_canSeek)
914  {
915  SeekCore(0L, SeekOrigin.Current);
916  }
917  else
918  {
919  _pos = 0L;
920  }
921  }
922 
923  [SecuritySafeCritical]
924  private static Win32Native.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share)
925  {
926  Win32Native.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES = null;
927  if ((share & FileShare.Inheritable) != 0)
928  {
929  sECURITY_ATTRIBUTES = new Win32Native.SECURITY_ATTRIBUTES();
930  sECURITY_ATTRIBUTES.nLength = Marshal.SizeOf(sECURITY_ATTRIBUTES);
931  sECURITY_ATTRIBUTES.bInheritHandle = 1;
932  }
933  return sECURITY_ATTRIBUTES;
934  }
935 
936  [SecuritySafeCritical]
937  private unsafe static Win32Native.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share, FileSecurity fileSecurity, out object pinningHandle)
938  {
939  pinningHandle = null;
940  Win32Native.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES = null;
941  if ((share & FileShare.Inheritable) != 0 || fileSecurity != null)
942  {
943  sECURITY_ATTRIBUTES = new Win32Native.SECURITY_ATTRIBUTES();
944  sECURITY_ATTRIBUTES.nLength = Marshal.SizeOf(sECURITY_ATTRIBUTES);
945  if ((share & FileShare.Inheritable) != 0)
946  {
947  sECURITY_ATTRIBUTES.bInheritHandle = 1;
948  }
949  if (fileSecurity != null)
950  {
951  byte[] securityDescriptorBinaryForm = fileSecurity.GetSecurityDescriptorBinaryForm();
952  pinningHandle = GCHandle.Alloc(securityDescriptorBinaryForm, GCHandleType.Pinned);
953  byte[] array = securityDescriptorBinaryForm;
954  fixed (byte* pSecurityDescriptor = array)
955  {
956  sECURITY_ATTRIBUTES.pSecurityDescriptor = pSecurityDescriptor;
957  }
958  }
959  }
960  return sECURITY_ATTRIBUTES;
961  }
962 
963  [SecuritySafeCritical]
964  private void VerifyHandleIsSync()
965  {
966  byte[] bytes = new byte[1];
967  int hr = 0;
968  int num = 0;
969  if (CanRead)
970  {
971  num = ReadFileNative(_handle, bytes, 0, 0, null, out hr);
972  }
973  else if (CanWrite)
974  {
975  num = WriteFileNative(_handle, bytes, 0, 0, null, out hr);
976  }
977  switch (hr)
978  {
979  case 87:
980  throw new ArgumentException(Environment.GetResourceString("Arg_HandleNotSync"));
981  case 6:
982  __Error.WinIOError(hr, "<OS handle>");
983  break;
984  }
985  }
986 
993  [SecuritySafeCritical]
995  {
996  if (_handle.IsClosed)
997  {
998  __Error.FileNotOpen();
999  }
1000  return new FileSecurity(_handle, _fileName, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
1001  }
1002 
1009  [SecuritySafeCritical]
1010  public void SetAccessControl(FileSecurity fileSecurity)
1011  {
1012  if (fileSecurity == null)
1013  {
1014  throw new ArgumentNullException("fileSecurity");
1015  }
1016  if (_handle.IsClosed)
1017  {
1018  __Error.FileNotOpen();
1019  }
1020  fileSecurity.Persist(_handle, _fileName);
1021  }
1022 
1026  [SecuritySafeCritical]
1027  protected override void Dispose(bool disposing)
1028  {
1029  try
1030  {
1031  if (_handle != null && !_handle.IsClosed && _writePos > 0)
1032  {
1033  FlushWrite(!disposing);
1034  }
1035  }
1036  finally
1037  {
1038  if (_handle != null && !_handle.IsClosed)
1039  {
1040  _handle.Dispose();
1041  }
1042  _canRead = false;
1043  _canWrite = false;
1044  _canSeek = false;
1045  base.Dispose(disposing);
1046  }
1047  }
1048 
1050  [SecuritySafeCritical]
1051  ~FileStream()
1052  {
1053  if (_handle != null)
1054  {
1055  Dispose(disposing: false);
1056  }
1057  }
1058 
1062  public override void Flush()
1063  {
1064  Flush(flushToDisk: false);
1065  }
1066 
1070  [SecuritySafeCritical]
1071  public virtual void Flush(bool flushToDisk)
1072  {
1073  if (_handle.IsClosed)
1074  {
1075  __Error.FileNotOpen();
1076  }
1077  FlushInternalBuffer();
1078  if (flushToDisk && CanWrite)
1079  {
1080  FlushOSBuffer();
1081  }
1082  }
1083 
1084  private void FlushInternalBuffer()
1085  {
1086  if (_writePos > 0)
1087  {
1088  FlushWrite(calledFromFinalizer: false);
1089  }
1090  else if (_readPos < _readLen && CanSeek)
1091  {
1092  FlushRead();
1093  }
1094  }
1095 
1096  [SecuritySafeCritical]
1097  private void FlushOSBuffer()
1098  {
1099  if (!Win32Native.FlushFileBuffers(_handle))
1100  {
1101  __Error.WinIOError();
1102  }
1103  }
1104 
1105  private void FlushRead()
1106  {
1107  if (_readPos - _readLen != 0)
1108  {
1109  SeekCore(_readPos - _readLen, SeekOrigin.Current);
1110  }
1111  _readPos = 0;
1112  _readLen = 0;
1113  }
1114 
1115  private void FlushWrite(bool calledFromFinalizer)
1116  {
1117  if (_isAsync)
1118  {
1119  IAsyncResult asyncResult = BeginWriteCore(_buffer, 0, _writePos, null, null);
1120  if (!calledFromFinalizer)
1121  {
1122  EndWrite(asyncResult);
1123  }
1124  }
1125  else
1126  {
1127  WriteCore(_buffer, 0, _writePos);
1128  }
1129  _writePos = 0;
1130  }
1131 
1137  [SecuritySafeCritical]
1138  public override void SetLength(long value)
1139  {
1140  if (value < 0)
1141  {
1142  throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1143  }
1144  if (_handle.IsClosed)
1145  {
1146  __Error.FileNotOpen();
1147  }
1148  if (!CanSeek)
1149  {
1150  __Error.SeekNotSupported();
1151  }
1152  if (!CanWrite)
1153  {
1154  __Error.WriteNotSupported();
1155  }
1156  if (_writePos > 0)
1157  {
1158  FlushWrite(calledFromFinalizer: false);
1159  }
1160  else if (_readPos < _readLen)
1161  {
1162  FlushRead();
1163  }
1164  _readPos = 0;
1165  _readLen = 0;
1166  if (_appendStart != -1 && value < _appendStart)
1167  {
1168  throw new IOException(Environment.GetResourceString("IO.IO_SetLengthAppendTruncate"));
1169  }
1170  SetLengthCore(value);
1171  }
1172 
1173  [SecuritySafeCritical]
1174  private void SetLengthCore(long value)
1175  {
1176  long pos = _pos;
1177  if (_exposedHandle)
1178  {
1179  VerifyOSHandlePosition();
1180  }
1181  if (_pos != value)
1182  {
1183  SeekCore(value, SeekOrigin.Begin);
1184  }
1185  if (!Win32Native.SetEndOfFile(_handle))
1186  {
1187  int lastWin32Error = Marshal.GetLastWin32Error();
1188  if (lastWin32Error == 87)
1189  {
1190  throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_FileLengthTooBig"));
1191  }
1192  __Error.WinIOError(lastWin32Error, string.Empty);
1193  }
1194  if (pos != value)
1195  {
1196  if (pos < value)
1197  {
1198  SeekCore(pos, SeekOrigin.Begin);
1199  }
1200  else
1201  {
1202  SeekCore(0L, SeekOrigin.End);
1203  }
1204  }
1205  }
1206 
1221  [SecuritySafeCritical]
1222  public override int Read([In] [Out] byte[] array, int offset, int count)
1223  {
1224  if (array == null)
1225  {
1226  throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
1227  }
1228  if (offset < 0)
1229  {
1230  throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1231  }
1232  if (count < 0)
1233  {
1234  throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1235  }
1236  if (array.Length - offset < count)
1237  {
1238  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
1239  }
1240  if (_handle.IsClosed)
1241  {
1242  __Error.FileNotOpen();
1243  }
1244  bool flag = false;
1245  int num = _readLen - _readPos;
1246  if (num == 0)
1247  {
1248  if (!CanRead)
1249  {
1250  __Error.ReadNotSupported();
1251  }
1252  if (_writePos > 0)
1253  {
1254  FlushWrite(calledFromFinalizer: false);
1255  }
1256  if (!CanSeek || count >= _bufferSize)
1257  {
1258  num = ReadCore(array, offset, count);
1259  _readPos = 0;
1260  _readLen = 0;
1261  return num;
1262  }
1263  if (_buffer == null)
1264  {
1265  _buffer = new byte[_bufferSize];
1266  }
1267  num = ReadCore(_buffer, 0, _bufferSize);
1268  if (num == 0)
1269  {
1270  return 0;
1271  }
1272  flag = (num < _bufferSize);
1273  _readPos = 0;
1274  _readLen = num;
1275  }
1276  if (num > count)
1277  {
1278  num = count;
1279  }
1280  Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, num);
1281  _readPos += num;
1282  if (!_isPipe && num < count && !flag)
1283  {
1284  int num2 = ReadCore(array, offset + num, count - num);
1285  num += num2;
1286  _readPos = 0;
1287  _readLen = 0;
1288  }
1289  return num;
1290  }
1291 
1292  [SecuritySafeCritical]
1293  private int ReadCore(byte[] buffer, int offset, int count)
1294  {
1295  if (_isAsync)
1296  {
1297  IAsyncResult asyncResult = BeginReadCore(buffer, offset, count, null, null, 0);
1298  return EndRead(asyncResult);
1299  }
1300  if (_exposedHandle)
1301  {
1302  VerifyOSHandlePosition();
1303  }
1304  int hr = 0;
1305  int num = ReadFileNative(_handle, buffer, offset, count, null, out hr);
1306  if (num == -1)
1307  {
1308  switch (hr)
1309  {
1310  case 109:
1311  num = 0;
1312  break;
1313  case 87:
1314  throw new ArgumentException(Environment.GetResourceString("Arg_HandleNotSync"));
1315  default:
1316  __Error.WinIOError(hr, string.Empty);
1317  break;
1318  }
1319  }
1320  _pos += num;
1321  return num;
1322  }
1323 
1332  [SecuritySafeCritical]
1333  public override long Seek(long offset, SeekOrigin origin)
1334  {
1335  if (origin < SeekOrigin.Begin || origin > SeekOrigin.End)
1336  {
1337  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
1338  }
1339  if (_handle.IsClosed)
1340  {
1341  __Error.FileNotOpen();
1342  }
1343  if (!CanSeek)
1344  {
1345  __Error.SeekNotSupported();
1346  }
1347  if (_writePos > 0)
1348  {
1349  FlushWrite(calledFromFinalizer: false);
1350  }
1351  else if (origin == SeekOrigin.Current)
1352  {
1353  offset -= _readLen - _readPos;
1354  }
1355  if (_exposedHandle)
1356  {
1357  VerifyOSHandlePosition();
1358  }
1359  long num = _pos + (_readPos - _readLen);
1360  long num2 = SeekCore(offset, origin);
1361  if (_appendStart != -1 && num2 < _appendStart)
1362  {
1363  SeekCore(num, SeekOrigin.Begin);
1364  throw new IOException(Environment.GetResourceString("IO.IO_SeekAppendOverwrite"));
1365  }
1366  if (_readLen > 0)
1367  {
1368  if (num == num2)
1369  {
1370  if (_readPos > 0)
1371  {
1372  Buffer.InternalBlockCopy(_buffer, _readPos, _buffer, 0, _readLen - _readPos);
1373  _readLen -= _readPos;
1374  _readPos = 0;
1375  }
1376  if (_readLen > 0)
1377  {
1378  SeekCore(_readLen, SeekOrigin.Current);
1379  }
1380  }
1381  else if (num - _readPos < num2 && num2 < num + _readLen - _readPos)
1382  {
1383  int num3 = (int)(num2 - num);
1384  Buffer.InternalBlockCopy(_buffer, _readPos + num3, _buffer, 0, _readLen - (_readPos + num3));
1385  _readLen -= _readPos + num3;
1386  _readPos = 0;
1387  if (_readLen > 0)
1388  {
1389  SeekCore(_readLen, SeekOrigin.Current);
1390  }
1391  }
1392  else
1393  {
1394  _readPos = 0;
1395  _readLen = 0;
1396  }
1397  }
1398  return num2;
1399  }
1400 
1401  [SecuritySafeCritical]
1402  private long SeekCore(long offset, SeekOrigin origin)
1403  {
1404  int hr = 0;
1405  long num = 0L;
1406  num = Win32Native.SetFilePointer(_handle, offset, origin, out hr);
1407  if (num == -1)
1408  {
1409  if (hr == 6)
1410  {
1411  _handle.Dispose();
1412  }
1413  __Error.WinIOError(hr, string.Empty);
1414  }
1415  _pos = num;
1416  return num;
1417  }
1418 
1419  private void VerifyOSHandlePosition()
1420  {
1421  if (!CanSeek)
1422  {
1423  return;
1424  }
1425  long pos = _pos;
1426  long num = SeekCore(0L, SeekOrigin.Current);
1427  if (num != pos)
1428  {
1429  _readPos = 0;
1430  _readLen = 0;
1431  if (_writePos > 0)
1432  {
1433  _writePos = 0;
1434  throw new IOException(Environment.GetResourceString("IO.IO_FileStreamHandlePosition"));
1435  }
1436  }
1437  }
1438 
1452  [SecuritySafeCritical]
1453  public override void Write(byte[] array, int offset, int count)
1454  {
1455  if (array == null)
1456  {
1457  throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
1458  }
1459  if (offset < 0)
1460  {
1461  throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1462  }
1463  if (count < 0)
1464  {
1465  throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1466  }
1467  if (array.Length - offset < count)
1468  {
1469  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
1470  }
1471  if (_handle.IsClosed)
1472  {
1473  __Error.FileNotOpen();
1474  }
1475  if (_writePos == 0)
1476  {
1477  if (!CanWrite)
1478  {
1479  __Error.WriteNotSupported();
1480  }
1481  if (_readPos < _readLen)
1482  {
1483  FlushRead();
1484  }
1485  _readPos = 0;
1486  _readLen = 0;
1487  }
1488  if (_writePos > 0)
1489  {
1490  int num = _bufferSize - _writePos;
1491  if (num > 0)
1492  {
1493  if (num > count)
1494  {
1495  num = count;
1496  }
1497  Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, num);
1498  _writePos += num;
1499  if (count == num)
1500  {
1501  return;
1502  }
1503  offset += num;
1504  count -= num;
1505  }
1506  if (_isAsync)
1507  {
1508  IAsyncResult asyncResult = BeginWriteCore(_buffer, 0, _writePos, null, null);
1509  EndWrite(asyncResult);
1510  }
1511  else
1512  {
1513  WriteCore(_buffer, 0, _writePos);
1514  }
1515  _writePos = 0;
1516  }
1517  if (count >= _bufferSize)
1518  {
1519  WriteCore(array, offset, count);
1520  }
1521  else if (count != 0)
1522  {
1523  if (_buffer == null)
1524  {
1525  _buffer = new byte[_bufferSize];
1526  }
1527  Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, count);
1528  _writePos = count;
1529  }
1530  }
1531 
1532  [SecuritySafeCritical]
1533  private void WriteCore(byte[] buffer, int offset, int count)
1534  {
1535  if (_isAsync)
1536  {
1537  IAsyncResult asyncResult = BeginWriteCore(buffer, offset, count, null, null);
1538  EndWrite(asyncResult);
1539  return;
1540  }
1541  if (_exposedHandle)
1542  {
1543  VerifyOSHandlePosition();
1544  }
1545  int hr = 0;
1546  int num = WriteFileNative(_handle, buffer, offset, count, null, out hr);
1547  if (num == -1)
1548  {
1549  switch (hr)
1550  {
1551  case 232:
1552  num = 0;
1553  break;
1554  case 87:
1555  throw new IOException(Environment.GetResourceString("IO.IO_FileTooLongOrHandleNotSync"));
1556  default:
1557  __Error.WinIOError(hr, string.Empty);
1558  break;
1559  }
1560  }
1561  _pos += num;
1562  }
1563 
1577  [SecuritySafeCritical]
1578  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1579  public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
1580  {
1581  if (array == null)
1582  {
1583  throw new ArgumentNullException("array");
1584  }
1585  if (offset < 0)
1586  {
1587  throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1588  }
1589  if (numBytes < 0)
1590  {
1591  throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1592  }
1593  if (array.Length - offset < numBytes)
1594  {
1595  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
1596  }
1597  if (_handle.IsClosed)
1598  {
1599  __Error.FileNotOpen();
1600  }
1601  if (!_isAsync)
1602  {
1603  return base.BeginRead(array, offset, numBytes, userCallback, stateObject);
1604  }
1605  return BeginReadAsync(array, offset, numBytes, userCallback, stateObject);
1606  }
1607 
1608  [SecuritySafeCritical]
1609  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1610  private FileStreamAsyncResult BeginReadAsync(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
1611  {
1612  if (!CanRead)
1613  {
1614  __Error.ReadNotSupported();
1615  }
1616  if (_isPipe)
1617  {
1618  if (_readPos < _readLen)
1619  {
1620  int num = _readLen - _readPos;
1621  if (num > numBytes)
1622  {
1623  num = numBytes;
1624  }
1625  Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, num);
1626  _readPos += num;
1627  return FileStreamAsyncResult.CreateBufferedReadResult(num, userCallback, stateObject, isWrite: false);
1628  }
1629  return BeginReadCore(array, offset, numBytes, userCallback, stateObject, 0);
1630  }
1631  if (_writePos > 0)
1632  {
1633  FlushWrite(calledFromFinalizer: false);
1634  }
1635  if (_readPos == _readLen)
1636  {
1637  if (numBytes < _bufferSize)
1638  {
1639  if (_buffer == null)
1640  {
1641  _buffer = new byte[_bufferSize];
1642  }
1643  IAsyncResult asyncResult = BeginReadCore(_buffer, 0, _bufferSize, null, null, 0);
1644  _readLen = EndRead(asyncResult);
1645  int num2 = _readLen;
1646  if (num2 > numBytes)
1647  {
1648  num2 = numBytes;
1649  }
1650  Buffer.InternalBlockCopy(_buffer, 0, array, offset, num2);
1651  _readPos = num2;
1652  return FileStreamAsyncResult.CreateBufferedReadResult(num2, userCallback, stateObject, isWrite: false);
1653  }
1654  _readPos = 0;
1655  _readLen = 0;
1656  return BeginReadCore(array, offset, numBytes, userCallback, stateObject, 0);
1657  }
1658  int num3 = _readLen - _readPos;
1659  if (num3 > numBytes)
1660  {
1661  num3 = numBytes;
1662  }
1663  Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, num3);
1664  _readPos += num3;
1665  if (num3 >= numBytes)
1666  {
1667  return FileStreamAsyncResult.CreateBufferedReadResult(num3, userCallback, stateObject, isWrite: false);
1668  }
1669  _readPos = 0;
1670  _readLen = 0;
1671  return BeginReadCore(array, offset + num3, numBytes - num3, userCallback, stateObject, num3);
1672  }
1673 
1674  [SecuritySafeCritical]
1675  private unsafe FileStreamAsyncResult BeginReadCore(byte[] bytes, int offset, int numBytes, AsyncCallback userCallback, object stateObject, int numBufferedBytesRead)
1676  {
1677  FileStreamAsyncResult fileStreamAsyncResult = new FileStreamAsyncResult(numBufferedBytesRead, bytes, _handle, userCallback, stateObject, isWrite: false);
1678  NativeOverlapped* overLapped = fileStreamAsyncResult.OverLapped;
1679  if (CanSeek)
1680  {
1681  long length = Length;
1682  if (_exposedHandle)
1683  {
1684  VerifyOSHandlePosition();
1685  }
1686  if (_pos + numBytes > length)
1687  {
1688  numBytes = (int)((_pos <= length) ? (length - _pos) : 0);
1689  }
1690  overLapped->OffsetLow = (int)_pos;
1691  overLapped->OffsetHigh = (int)(_pos >> 32);
1692  SeekCore(numBytes, SeekOrigin.Current);
1693  }
1694  if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, (EventKeywords)16L))
1695  {
1696  FrameworkEventSource.Log.ThreadTransferSend((long)fileStreamAsyncResult.OverLapped, 2, string.Empty, multiDequeues: false);
1697  }
1698  int hr = 0;
1699  int num = ReadFileNative(_handle, bytes, offset, numBytes, overLapped, out hr);
1700  if (num == -1 && numBytes != -1)
1701  {
1702  switch (hr)
1703  {
1704  case 109:
1705  overLapped->InternalLow = IntPtr.Zero;
1706  fileStreamAsyncResult.CallUserCallback();
1707  break;
1708  default:
1709  if (!_handle.IsClosed && CanSeek)
1710  {
1711  SeekCore(0L, SeekOrigin.Current);
1712  }
1713  if (hr == 38)
1714  {
1715  __Error.EndOfFile();
1716  }
1717  else
1718  {
1719  __Error.WinIOError(hr, string.Empty);
1720  }
1721  break;
1722  case 997:
1723  break;
1724  }
1725  }
1726  return fileStreamAsyncResult;
1727  }
1728 
1738  [SecuritySafeCritical]
1739  public override int EndRead(IAsyncResult asyncResult)
1740  {
1741  if (asyncResult == null)
1742  {
1743  throw new ArgumentNullException("asyncResult");
1744  }
1745  if (!_isAsync)
1746  {
1747  return base.EndRead(asyncResult);
1748  }
1749  FileStreamAsyncResult fileStreamAsyncResult = asyncResult as FileStreamAsyncResult;
1750  if (fileStreamAsyncResult == null || fileStreamAsyncResult.IsWrite)
1751  {
1752  __Error.WrongAsyncResult();
1753  }
1754  if (1 == Interlocked.CompareExchange(ref fileStreamAsyncResult._EndXxxCalled, 1, 0))
1755  {
1756  __Error.EndReadCalledTwice();
1757  }
1758  fileStreamAsyncResult.Wait();
1759  fileStreamAsyncResult.ReleaseNativeResource();
1760  if (fileStreamAsyncResult.ErrorCode != 0)
1761  {
1762  __Error.WinIOError(fileStreamAsyncResult.ErrorCode, string.Empty);
1763  }
1764  return fileStreamAsyncResult.NumBytesRead;
1765  }
1766 
1771  [SecuritySafeCritical]
1772  public override int ReadByte()
1773  {
1774  if (_handle.IsClosed)
1775  {
1776  __Error.FileNotOpen();
1777  }
1778  if (_readLen == 0 && !CanRead)
1779  {
1780  __Error.ReadNotSupported();
1781  }
1782  if (_readPos == _readLen)
1783  {
1784  if (_writePos > 0)
1785  {
1786  FlushWrite(calledFromFinalizer: false);
1787  }
1788  if (_buffer == null)
1789  {
1790  _buffer = new byte[_bufferSize];
1791  }
1792  _readLen = ReadCore(_buffer, 0, _bufferSize);
1793  _readPos = 0;
1794  }
1795  if (_readPos == _readLen)
1796  {
1797  return -1;
1798  }
1799  int result = _buffer[_readPos];
1800  _readPos++;
1801  return result;
1802  }
1803 
1820  [SecuritySafeCritical]
1821  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1822  public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
1823  {
1824  if (array == null)
1825  {
1826  throw new ArgumentNullException("array");
1827  }
1828  if (offset < 0)
1829  {
1830  throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1831  }
1832  if (numBytes < 0)
1833  {
1834  throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
1835  }
1836  if (array.Length - offset < numBytes)
1837  {
1838  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
1839  }
1840  if (_handle.IsClosed)
1841  {
1842  __Error.FileNotOpen();
1843  }
1844  if (!_isAsync)
1845  {
1846  return base.BeginWrite(array, offset, numBytes, userCallback, stateObject);
1847  }
1848  return BeginWriteAsync(array, offset, numBytes, userCallback, stateObject);
1849  }
1850 
1851  [SecuritySafeCritical]
1852  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1853  private FileStreamAsyncResult BeginWriteAsync(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
1854  {
1855  if (!CanWrite)
1856  {
1857  __Error.WriteNotSupported();
1858  }
1859  if (_isPipe)
1860  {
1861  if (_writePos > 0)
1862  {
1863  FlushWrite(calledFromFinalizer: false);
1864  }
1865  return BeginWriteCore(array, offset, numBytes, userCallback, stateObject);
1866  }
1867  if (_writePos == 0)
1868  {
1869  if (_readPos < _readLen)
1870  {
1871  FlushRead();
1872  }
1873  _readPos = 0;
1874  _readLen = 0;
1875  }
1876  int num = _bufferSize - _writePos;
1877  if (numBytes <= num)
1878  {
1879  if (_writePos == 0)
1880  {
1881  _buffer = new byte[_bufferSize];
1882  }
1883  Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, numBytes);
1884  _writePos += numBytes;
1885  return FileStreamAsyncResult.CreateBufferedReadResult(numBytes, userCallback, stateObject, isWrite: true);
1886  }
1887  if (_writePos > 0)
1888  {
1889  FlushWrite(calledFromFinalizer: false);
1890  }
1891  return BeginWriteCore(array, offset, numBytes, userCallback, stateObject);
1892  }
1893 
1894  [SecuritySafeCritical]
1895  private unsafe FileStreamAsyncResult BeginWriteCore(byte[] bytes, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
1896  {
1897  FileStreamAsyncResult fileStreamAsyncResult = new FileStreamAsyncResult(0, bytes, _handle, userCallback, stateObject, isWrite: true);
1898  NativeOverlapped* overLapped = fileStreamAsyncResult.OverLapped;
1899  if (CanSeek)
1900  {
1901  long length = Length;
1902  if (_exposedHandle)
1903  {
1904  VerifyOSHandlePosition();
1905  }
1906  if (_pos + numBytes > length)
1907  {
1908  SetLengthCore(_pos + numBytes);
1909  }
1910  overLapped->OffsetLow = (int)_pos;
1911  overLapped->OffsetHigh = (int)(_pos >> 32);
1912  SeekCore(numBytes, SeekOrigin.Current);
1913  }
1914  if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, (EventKeywords)16L))
1915  {
1916  FrameworkEventSource.Log.ThreadTransferSend((long)fileStreamAsyncResult.OverLapped, 2, string.Empty, multiDequeues: false);
1917  }
1918  int hr = 0;
1919  int num = WriteFileNative(_handle, bytes, offset, numBytes, overLapped, out hr);
1920  if (num == -1 && numBytes != -1)
1921  {
1922  switch (hr)
1923  {
1924  case 232:
1925  fileStreamAsyncResult.CallUserCallback();
1926  break;
1927  default:
1928  if (!_handle.IsClosed && CanSeek)
1929  {
1930  SeekCore(0L, SeekOrigin.Current);
1931  }
1932  if (hr == 38)
1933  {
1934  __Error.EndOfFile();
1935  }
1936  else
1937  {
1938  __Error.WinIOError(hr, string.Empty);
1939  }
1940  break;
1941  case 997:
1942  break;
1943  }
1944  }
1945  return fileStreamAsyncResult;
1946  }
1947 
1956  [SecuritySafeCritical]
1957  public override void EndWrite(IAsyncResult asyncResult)
1958  {
1959  if (asyncResult == null)
1960  {
1961  throw new ArgumentNullException("asyncResult");
1962  }
1963  if (!_isAsync)
1964  {
1965  base.EndWrite(asyncResult);
1966  return;
1967  }
1968  FileStreamAsyncResult fileStreamAsyncResult = asyncResult as FileStreamAsyncResult;
1969  if (fileStreamAsyncResult == null || !fileStreamAsyncResult.IsWrite)
1970  {
1971  __Error.WrongAsyncResult();
1972  }
1973  if (1 == Interlocked.CompareExchange(ref fileStreamAsyncResult._EndXxxCalled, 1, 0))
1974  {
1975  __Error.EndWriteCalledTwice();
1976  }
1977  fileStreamAsyncResult.Wait();
1978  fileStreamAsyncResult.ReleaseNativeResource();
1979  if (fileStreamAsyncResult.ErrorCode != 0)
1980  {
1981  __Error.WinIOError(fileStreamAsyncResult.ErrorCode, string.Empty);
1982  }
1983  }
1984 
1989  [SecuritySafeCritical]
1990  public override void WriteByte(byte value)
1991  {
1992  if (_handle.IsClosed)
1993  {
1994  __Error.FileNotOpen();
1995  }
1996  if (_writePos == 0)
1997  {
1998  if (!CanWrite)
1999  {
2000  __Error.WriteNotSupported();
2001  }
2002  if (_readPos < _readLen)
2003  {
2004  FlushRead();
2005  }
2006  _readPos = 0;
2007  _readLen = 0;
2008  if (_buffer == null)
2009  {
2010  _buffer = new byte[_bufferSize];
2011  }
2012  }
2013  if (_writePos == _bufferSize)
2014  {
2015  FlushWrite(calledFromFinalizer: false);
2016  }
2017  _buffer[_writePos] = value;
2018  _writePos++;
2019  }
2020 
2028  [SecuritySafeCritical]
2029  public virtual void Lock(long position, long length)
2030  {
2031  if (position < 0 || length < 0)
2032  {
2033  throw new ArgumentOutOfRangeException((position < 0) ? "position" : "length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
2034  }
2035  if (_handle.IsClosed)
2036  {
2037  __Error.FileNotOpen();
2038  }
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))
2044  {
2045  __Error.WinIOError();
2046  }
2047  }
2048 
2054  [SecuritySafeCritical]
2055  public virtual void Unlock(long position, long length)
2056  {
2057  if (position < 0 || length < 0)
2058  {
2059  throw new ArgumentOutOfRangeException((position < 0) ? "position" : "length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
2060  }
2061  if (_handle.IsClosed)
2062  {
2063  __Error.FileNotOpen();
2064  }
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))
2070  {
2071  __Error.WinIOError();
2072  }
2073  }
2074 
2075  [SecurityCritical]
2076  private unsafe int ReadFileNative(SafeFileHandle handle, byte[] bytes, int offset, int count, NativeOverlapped* overlapped, out int hr)
2077  {
2078  if (bytes.Length - offset < count)
2079  {
2080  throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition"));
2081  }
2082  if (bytes.Length == 0)
2083  {
2084  hr = 0;
2085  return 0;
2086  }
2087  int num = 0;
2088  int numBytesRead = 0;
2089  fixed (byte* ptr = bytes)
2090  {
2091  num = ((!_isAsync) ? Win32Native.ReadFile(handle, ptr + offset, count, out numBytesRead, IntPtr.Zero) : Win32Native.ReadFile(handle, ptr + offset, count, IntPtr.Zero, overlapped));
2092  }
2093  if (num == 0)
2094  {
2095  hr = Marshal.GetLastWin32Error();
2096  if (hr == 109 || hr == 233)
2097  {
2098  return -1;
2099  }
2100  if (hr == 6)
2101  {
2102  _handle.Dispose();
2103  }
2104  return -1;
2105  }
2106  hr = 0;
2107  return numBytesRead;
2108  }
2109 
2110  [SecurityCritical]
2111  private unsafe int WriteFileNative(SafeFileHandle handle, byte[] bytes, int offset, int count, NativeOverlapped* overlapped, out int hr)
2112  {
2113  if (bytes.Length - offset < count)
2114  {
2115  throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition"));
2116  }
2117  if (bytes.Length == 0)
2118  {
2119  hr = 0;
2120  return 0;
2121  }
2122  int numBytesWritten = 0;
2123  int num = 0;
2124  fixed (byte* ptr = bytes)
2125  {
2126  num = ((!_isAsync) ? Win32Native.WriteFile(handle, ptr + offset, count, out numBytesWritten, IntPtr.Zero) : Win32Native.WriteFile(handle, ptr + offset, count, IntPtr.Zero, overlapped));
2127  }
2128  if (num == 0)
2129  {
2130  hr = Marshal.GetLastWin32Error();
2131  if (hr == 232)
2132  {
2133  return -1;
2134  }
2135  if (hr == 6)
2136  {
2137  _handle.Dispose();
2138  }
2139  return -1;
2140  }
2141  hr = 0;
2142  return numBytesWritten;
2143  }
2144 
2159  [ComVisible(false)]
2160  [SecuritySafeCritical]
2161  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2162  public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
2163  {
2164  if (buffer == null)
2165  {
2166  throw new ArgumentNullException("buffer");
2167  }
2168  if (offset < 0)
2169  {
2170  throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
2171  }
2172  if (count < 0)
2173  {
2174  throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
2175  }
2176  if (buffer.Length - offset < count)
2177  {
2178  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
2179  }
2180  if (GetType() != typeof(FileStream))
2181  {
2182  return base.ReadAsync(buffer, offset, count, cancellationToken);
2183  }
2184  if (cancellationToken.IsCancellationRequested)
2185  {
2186  return Task.FromCancellation<int>(cancellationToken);
2187  }
2188  if (_handle.IsClosed)
2189  {
2190  __Error.FileNotOpen();
2191  }
2192  if (!_isAsync)
2193  {
2194  return base.ReadAsync(buffer, offset, count, cancellationToken);
2195  }
2196  FileStreamReadWriteTask<int> fileStreamReadWriteTask = new FileStreamReadWriteTask<int>(cancellationToken);
2197  AsyncCallback userCallback = EndReadTask;
2198  fileStreamReadWriteTask._asyncResult = BeginReadAsync(buffer, offset, count, userCallback, fileStreamReadWriteTask);
2199  if (fileStreamReadWriteTask._asyncResult.IsAsync && cancellationToken.CanBeCanceled)
2200  {
2201  Action<object> callback = FileStream.CancelTask<int>;
2202  fileStreamReadWriteTask._registration = cancellationToken.Register(callback, fileStreamReadWriteTask);
2203  if (fileStreamReadWriteTask._asyncResult.IsCompleted)
2204  {
2205  fileStreamReadWriteTask._registration.Dispose();
2206  }
2207  }
2208  return fileStreamReadWriteTask;
2209  }
2210 
2225  [ComVisible(false)]
2226  [SecuritySafeCritical]
2227  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2228  public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
2229  {
2230  if (buffer == null)
2231  {
2232  throw new ArgumentNullException("buffer");
2233  }
2234  if (offset < 0)
2235  {
2236  throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
2237  }
2238  if (count < 0)
2239  {
2240  throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
2241  }
2242  if (buffer.Length - offset < count)
2243  {
2244  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
2245  }
2246  if (GetType() != typeof(FileStream))
2247  {
2248  return base.WriteAsync(buffer, offset, count, cancellationToken);
2249  }
2250  if (cancellationToken.IsCancellationRequested)
2251  {
2252  return Task.FromCancellation(cancellationToken);
2253  }
2254  if (_handle.IsClosed)
2255  {
2256  __Error.FileNotOpen();
2257  }
2258  if (!_isAsync)
2259  {
2260  return base.WriteAsync(buffer, offset, count, cancellationToken);
2261  }
2262  FileStreamReadWriteTask<VoidTaskResult> fileStreamReadWriteTask = new FileStreamReadWriteTask<VoidTaskResult>(cancellationToken);
2263  AsyncCallback userCallback = EndWriteTask;
2264  fileStreamReadWriteTask._asyncResult = BeginWriteAsync(buffer, offset, count, userCallback, fileStreamReadWriteTask);
2265  if (fileStreamReadWriteTask._asyncResult.IsAsync && cancellationToken.CanBeCanceled)
2266  {
2267  Action<object> callback = FileStream.CancelTask<VoidTaskResult>;
2268  fileStreamReadWriteTask._registration = cancellationToken.Register(callback, fileStreamReadWriteTask);
2269  if (fileStreamReadWriteTask._asyncResult.IsCompleted)
2270  {
2271  fileStreamReadWriteTask._registration.Dispose();
2272  }
2273  }
2274  return fileStreamReadWriteTask;
2275  }
2276 
2277  [SecuritySafeCritical]
2278  private static void CancelTask<T>(object state)
2279  {
2280  FileStreamReadWriteTask<T> fileStreamReadWriteTask = state as FileStreamReadWriteTask<T>;
2281  FileStreamAsyncResult asyncResult = fileStreamReadWriteTask._asyncResult;
2282  try
2283  {
2284  if (!asyncResult.IsCompleted)
2285  {
2286  asyncResult.Cancel();
2287  }
2288  }
2289  catch (Exception exceptionObject)
2290  {
2291  fileStreamReadWriteTask.TrySetException(exceptionObject);
2292  }
2293  }
2294 
2295  [SecuritySafeCritical]
2296  private static void EndReadTask(IAsyncResult iar)
2297  {
2298  FileStreamAsyncResult fileStreamAsyncResult = iar as FileStreamAsyncResult;
2299  FileStreamReadWriteTask<int> fileStreamReadWriteTask = fileStreamAsyncResult.AsyncState as FileStreamReadWriteTask<int>;
2300  try
2301  {
2302  if (fileStreamAsyncResult.IsAsync)
2303  {
2304  fileStreamAsyncResult.ReleaseNativeResource();
2305  fileStreamReadWriteTask._registration.Dispose();
2306  }
2307  if (fileStreamAsyncResult.ErrorCode == 995)
2308  {
2309  CancellationToken cancellationToken = fileStreamReadWriteTask._cancellationToken;
2310  fileStreamReadWriteTask.TrySetCanceled(cancellationToken);
2311  }
2312  else
2313  {
2314  fileStreamReadWriteTask.TrySetResult(fileStreamAsyncResult.NumBytesRead);
2315  }
2316  }
2317  catch (Exception exceptionObject)
2318  {
2319  fileStreamReadWriteTask.TrySetException(exceptionObject);
2320  }
2321  }
2322 
2323  [SecuritySafeCritical]
2324  private static void EndWriteTask(IAsyncResult iar)
2325  {
2326  FileStreamAsyncResult fileStreamAsyncResult = iar as FileStreamAsyncResult;
2327  FileStreamReadWriteTask<VoidTaskResult> fileStreamReadWriteTask = iar.AsyncState as FileStreamReadWriteTask<VoidTaskResult>;
2328  try
2329  {
2330  if (fileStreamAsyncResult.IsAsync)
2331  {
2332  fileStreamAsyncResult.ReleaseNativeResource();
2333  fileStreamReadWriteTask._registration.Dispose();
2334  }
2335  if (fileStreamAsyncResult.ErrorCode == 995)
2336  {
2337  CancellationToken cancellationToken = fileStreamReadWriteTask._cancellationToken;
2338  fileStreamReadWriteTask.TrySetCanceled(cancellationToken);
2339  }
2340  else
2341  {
2342  fileStreamReadWriteTask.TrySetResult(default(VoidTaskResult));
2343  }
2344  }
2345  catch (Exception exceptionObject)
2346  {
2347  fileStreamReadWriteTask.TrySetException(exceptionObject);
2348  }
2349  }
2350 
2355  [ComVisible(false)]
2356  [SecuritySafeCritical]
2357  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2358  public override Task FlushAsync(CancellationToken cancellationToken)
2359  {
2360  if (GetType() != typeof(FileStream))
2361  {
2362  return base.FlushAsync(cancellationToken);
2363  }
2364  if (cancellationToken.IsCancellationRequested)
2365  {
2366  return Task.FromCancellation(cancellationToken);
2367  }
2368  if (_handle.IsClosed)
2369  {
2370  __Error.FileNotOpen();
2371  }
2372  try
2373  {
2374  FlushInternalBuffer();
2375  }
2376  catch (Exception exception)
2377  {
2378  return Task.FromException(exception);
2379  }
2380  if (CanWrite)
2381  {
2382  return Task.Factory.StartNew(delegate(object state)
2383  {
2384  ((FileStream)state).FlushOSBuffer();
2385  }, this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
2386  }
2387  return Task.CompletedTask;
2388  }
2389  }
2390 }
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,...
Definition: FileStream.cs:866
static new TaskFactory< TResult > Factory
Provides access to factory methods for creating and configuring T:System.Threading....
Definition: Task.cs:75
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,...
Definition: FileStream.cs:819
Propagates notification that operations should be canceled.
string Name
Gets the name of the FileStream that was passed to the constructor.
Definition: FileStream.cs:161
FileOptions
Represents advanced options for creating a T:System.IO.FileStream object.
Definition: FileOptions.cs:9
virtual void Unlock(long position, long length)
Allows access by other processes to all or part of a file that was previously locked.
Definition: FileStream.cs:2055
FileStream(SafeFileHandle handle, FileAccess access, int bufferSize)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
Definition: FileStream.cs:848
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,...
Definition: FileStream.cs:498
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....
Definition: FileStream.cs:1579
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.
Definition: EventKeywords.cs:6
FileMode
Specifies how the operating system should open a file.
Definition: FileMode.cs:8
Represents the access control and audit security for a file. This class cannot be inherited.
Definition: FileSecurity.cs:8
Represents an object that handles the low-level work of queuing tasks onto threads.
Definition: __Canon.cs:3
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.
Definition: Marshal.cs:159
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.
Definition: FileStream.cs:1453
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...
Definition: FileStream.cs:2228
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 ...
Definition: FileStream.cs:994
override void Dispose(bool disposing)
Releases the unmanaged resources used by the T:System.IO.FileStream and optionally releases the manag...
Definition: FileStream.cs:1027
FileStream(SafeFileHandle handle, FileAccess access)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
Definition: FileStream.cs:833
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.
Definition: FileStream.cs:1222
static string GetFileName(string path)
Returns the file name and extension of the specified path string.
Definition: Path.cs:914
bool IsCancellationRequested
Gets whether cancellation has been requested for this token.
SeekOrigin
Specifies the position in a stream to use for seeking.
Definition: SeekOrigin.cs:9
override bool CanWrite
Gets a value indicating whether the current stream supports writing.
Definition: FileStream.cs:108
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,...
Definition: FileStream.cs:455
override long Position
Gets or sets the current position of this stream.
Definition: FileStream.cs:193
EventLevel
Identifies the level of an event.
Definition: EventLevel.cs:5
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,...
Definition: FileStream.cs:780
SecurityAction
Specifies the security actions that can be performed using declarative security.
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
Represents the status of an asynchronous operation.
Definition: IAsyncResult.cs:9
The file is a directory.
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.
Definition: FileStream.cs:113
override void WriteByte(byte value)
Writes a byte to the current position in the file stream.
Definition: FileStream.cs:1990
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,...
Definition: FileStream.cs:394
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...
Definition: FileStream.cs:15
FileStream(string path, FileMode mode, FileAccess access)
Initializes a new instance of the T:System.IO.FileStream class with the specified path,...
Definition: FileStream.cs:310
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.
Definition: Task.cs:4130
The exception that is thrown when an I/O error occurs.
Definition: IOException.cs:10
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,...
Definition: FileStream.cs:797
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...
Definition: FileStream.cs:2162
Defines the underlying structure of all code access permissions.
A platform-specific type that is used to represent a pointer or a handle.
Definition: IntPtr.cs:14
override void EndWrite(IAsyncResult asyncResult)
Ends an asynchronous write operation and blocks until the I/O operation is complete....
Definition: FileStream.cs:1957
override bool CanRead
Gets a value indicating whether the current stream supports reading.
Definition: FileStream.cs:103
static GCHandle Alloc(object value)
Allocates a F:System.Runtime.InteropServices.GCHandleType.Normal handle for the specified object.
Definition: GCHandle.cs:98
virtual void Lock(long position, long length)
Prevents other processes from reading from or writing to the T:System.IO.FileStream.
Definition: FileStream.cs:2029
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,...
Definition: Marshal.cs:15
GCHandleType
Represents the types of handles the T:System.Runtime.InteropServices.GCHandle class can allocate.
Definition: GCHandleType.cs:7
Indicates that a file can be used for asynchronous reading and writing.
Provides a way to access a managed object from unmanaged memory.
Definition: GCHandle.cs:10
static Task CompletedTask
Gets a task that has already completed successfully.
Definition: Task.cs:1453
override int ReadByte()
Reads a byte from the file and advances the read position one byte.
Definition: FileStream.cs:1772
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.
Definition: FileStream.cs:1062
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.
Definition: FileStream.cs:126
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....
Definition: FileStream.cs:1822
static bool BindHandle(IntPtr osHandle)
Binds an operating system handle to the T:System.Threading.ThreadPool.
Definition: ThreadPool.cs:551
virtual SafeFileHandle SafeFileHandle
Gets a T:Microsoft.Win32.SafeHandles.SafeFileHandle object that represents the operating system file ...
Definition: FileStream.cs:249
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
FileAccess
Defines constants for read, write, or read/write access to a file.
Definition: FileAccess.cs:9
static readonly IntPtr Zero
A read-only field that represents a pointer or handle that has been initialized to zero.
Definition: IntPtr.cs:20
override Task FlushAsync(CancellationToken cancellationToken)
Asynchronously clears all buffers for this stream, causes any buffered data to be written to the unde...
Definition: FileStream.cs:2358
void Dispose()
Releases all resources used by the T:System.IO.Stream.
Definition: Stream.cs:863
Manipulates arrays of primitive types.
Definition: Buffer.cs:11
FileStream(IntPtr handle, FileAccess access)
Initializes a new instance of the T:System.IO.FileStream class for the specified file handle,...
Definition: FileStream.cs:764
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,...
Definition: FileStream.cs:364
virtual bool IsAsync
Gets a value indicating whether the FileStream was opened asynchronously or synchronously.
Definition: FileStream.cs:118
void SetAccessControl(FileSecurity fileSecurity)
Applies access control list (ACL) entries described by a T:System.Security.AccessControl....
Definition: FileStream.cs:1010
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.
Definition: FileStream.cs:1333
virtual void Flush(bool flushToDisk)
Clears buffers for this stream and causes any buffered data to be written to the file,...
Definition: FileStream.cs:1071
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.
Definition: Interlocked.cs:10
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.
Definition: FileStream.cs:232
Performs operations on T:System.String instances that contain file or directory path information....
Definition: Path.cs:13
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.
Definition: FileStream.cs:1138
FileStream(string path, FileMode mode, FileAccess access, FileShare share)
Initializes a new instance of the T:System.IO.FileStream class with the specified path,...
Definition: FileStream.cs:336
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I...
Definition: ThreadPool.cs:14
FileShare
Contains constants for controlling the kind of access other T:System.IO.FileStream objects can have t...
Definition: FileShare.cs:9
override int EndRead(IAsyncResult asyncResult)
Waits for the pending asynchronous read operation to complete. (Consider using M:System....
Definition: FileStream.cs:1739
Represents an asynchronous operation that can return a value.
Definition: Task.cs:18
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Definition: Stream.cs:16