2 // System.IO.FileStream.cs
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Dan Lewis (dihlewis@yahoo.co.uk)
7 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // Marek Safar (marek.safar@gmail.com)
10 // (C) 2001-2003 Ximian, Inc. http://www.ximian.com
11 // Copyright (C) 2004-2005, 2008, 2010 Novell, Inc (http://www.novell.com)
12 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Collections;
35 using System.Globalization;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
38 using System.Runtime.Remoting.Messaging;
39 using System.Security;
40 using System.Security.Permissions;
41 using System.Threading;
42 using Microsoft.Win32.SafeHandles;
45 using System.IO.IsolatedStorage;
47 using System.Security.AccessControl;
50 using System.Threading.Tasks;
55 public class FileStream : Stream
57 // construct from handle
59 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
60 public FileStream (IntPtr handle, FileAccess access)
61 : this (handle, access, true, DefaultBufferSize, false, false) {}
63 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
64 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle)
65 : this (handle, access, ownsHandle, DefaultBufferSize, false, false) {}
67 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")]
68 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
69 : this (handle, access, ownsHandle, bufferSize, false, false) {}
71 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")]
72 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
73 : this (handle, access, ownsHandle, bufferSize, isAsync, false) {}
75 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
76 internal FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isZeroSize)
78 if (handle == MonoIO.InvalidHandle)
79 throw new ArgumentException ("handle", Locale.GetText ("Invalid."));
81 Init (new SafeFileHandle (handle, false), access, ownsHandle, bufferSize, isAsync, isZeroSize);
84 // construct from filename
86 public FileStream (string path, FileMode mode)
87 : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.Read, DefaultBufferSize, false, FileOptions.None)
91 public FileStream (string path, FileMode mode, FileAccess access)
92 : this (path, mode, access, access == FileAccess.Write ? FileShare.None : FileShare.Read, DefaultBufferSize, false, false)
96 public FileStream (string path, FileMode mode, FileAccess access, FileShare share)
97 : this (path, mode, access, share, DefaultBufferSize, false, FileOptions.None)
101 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
102 : this (path, mode, access, share, bufferSize, false, FileOptions.None)
106 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
107 : this (path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
111 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
112 : this (path, mode, access, share, bufferSize, false, options)
117 public FileStream (SafeFileHandle handle, FileAccess access)
118 :this(handle, access, DefaultBufferSize, false)
122 public FileStream (SafeFileHandle handle, FileAccess access,
124 :this(handle, access, bufferSize, false)
128 public FileStream (SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
130 Init (handle, access, false, bufferSize, isAsync, false);
133 [MonoLimitation ("This ignores the rights parameter")]
134 public FileStream (string path, FileMode mode,
135 FileSystemRights rights, FileShare share,
136 int bufferSize, FileOptions options)
137 : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
141 [MonoLimitation ("This ignores the rights and fileSecurity parameters")]
142 public FileStream (string path, FileMode mode,
143 FileSystemRights rights, FileShare share,
144 int bufferSize, FileOptions options,
145 FileSecurity fileSecurity)
146 : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
151 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath = false, bool checkHost = false)
152 : this (path, mode, access, share, bufferSize, false, options)
156 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool isAsync, bool anonymous)
157 : this (path, mode, access, share, bufferSize, anonymous, isAsync ? FileOptions.Asynchronous : FileOptions.None)
161 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool anonymous, FileOptions options)
164 throw new ArgumentNullException ("path");
167 if (path.Length == 0) {
168 throw new ArgumentException ("Path is empty");
171 this.anonymous = anonymous;
172 // ignore the Inheritable flag
173 share &= ~FileShare.Inheritable;
176 throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
178 if (mode < FileMode.CreateNew || mode > FileMode.Append) {
181 throw new ArgumentException ("mode", "Enum value was out of legal range.");
184 throw new ArgumentOutOfRangeException ("mode", "Enum value was out of legal range.");
187 if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
188 throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
191 if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
192 throw new ArgumentOutOfRangeException ("share", "Enum value was out of legal range.");
195 if (path.IndexOfAny (Path.InvalidPathChars) != -1) {
196 throw new ArgumentException ("Name has invalid chars");
199 if (Directory.Exists (path)) {
200 // don't leak the path information for isolated storage
201 string msg = Locale.GetText ("Access to the path '{0}' is denied.");
202 throw new UnauthorizedAccessException (String.Format (msg, GetSecureFileName (path, false)));
205 /* Append streams can't be read (see FileMode
208 if (mode==FileMode.Append &&
209 (access&FileAccess.Read)==FileAccess.Read) {
210 throw new ArgumentException("Append access can be requested only in write-only mode.");
213 if ((access & FileAccess.Write) == 0 &&
214 (mode != FileMode.Open && mode != FileMode.OpenOrCreate)) {
215 string msg = Locale.GetText ("Combining FileMode: {0} with " +
216 "FileAccess: {1} is invalid.");
217 throw new ArgumentException (string.Format (msg, access, mode));
220 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
223 if (Path.DirectorySeparatorChar != '/' && path.IndexOf ('/') >= 0)
224 dname = Path.GetDirectoryName (Path.GetFullPath (path));
226 dname = Path.GetDirectoryName (path);
227 if (dname.Length > 0) {
228 string fp = Path.GetFullPath (dname);
229 if (!Directory.Exists (fp)) {
230 // don't leak the path information for isolated storage
231 string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
232 string fname = (anonymous) ? dname : Path.GetFullPath (path);
233 throw new DirectoryNotFoundException (String.Format (msg, fname));
237 if (access == FileAccess.Read && mode != FileMode.Create && mode != FileMode.OpenOrCreate &&
238 mode != FileMode.CreateNew && !File.Exists (path)) {
239 // don't leak the path information for isolated storage
240 string msg = Locale.GetText ("Could not find file \"{0}\".");
241 string fname = GetSecureFileName (path);
242 throw new FileNotFoundException (String.Format (msg, fname), fname);
245 // IsolatedStorage needs to keep the Name property to the default "[Unknown]"
249 // TODO: demand permissions
253 var nativeHandle = MonoIO.Open (path, mode, access, share, options, out error);
255 if (nativeHandle == MonoIO.InvalidHandle) {
256 // don't leak the path information for isolated storage
257 throw MonoIO.GetException (GetSecureFileName (path), error);
260 this.safeHandle = new SafeFileHandle (nativeHandle, false);
262 this.access = access;
265 /* Can we open non-files by name? */
267 if (MonoIO.GetFileType (safeHandle, out error) == MonoFileType.Disk) {
269 this.async = (options & FileOptions.Asynchronous) != 0;
271 this.canseek = false;
276 if (access == FileAccess.Read && canseek && (bufferSize == DefaultBufferSize)) {
277 /* Avoid allocating a large buffer for small files */
279 if (bufferSize > len) {
280 bufferSize = (int)(len < 1000 ? 1000 : len);
284 InitBuffer (bufferSize, false);
286 if (mode==FileMode.Append) {
287 this.Seek (0, SeekOrigin.End);
288 this.append_startpos=this.Position;
290 this.append_startpos=0;
294 private void Init (SafeFileHandle safeHandle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isZeroSize)
296 if (access < FileAccess.Read || access > FileAccess.ReadWrite)
297 throw new ArgumentOutOfRangeException ("access");
300 MonoFileType ftype = MonoIO.GetFileType (safeHandle, out error);
302 if (error != MonoIOError.ERROR_SUCCESS) {
303 throw MonoIO.GetException (name, error);
306 if (ftype == MonoFileType.Unknown) {
307 throw new IOException ("Invalid handle.");
308 } else if (ftype == MonoFileType.Disk) {
311 this.canseek = false;
314 this.safeHandle = safeHandle;
316 this.access = access;
317 this.owner = ownsHandle;
318 this.async = isAsync;
319 this.anonymous = false;
322 buf_start = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
323 if (error != MonoIOError.ERROR_SUCCESS) {
324 throw MonoIO.GetException (name, error);
328 /* Can't set append mode */
329 this.append_startpos=0;
334 public override bool CanRead {
336 return access == FileAccess.Read ||
337 access == FileAccess.ReadWrite;
341 public override bool CanWrite {
343 return access == FileAccess.Write ||
344 access == FileAccess.ReadWrite;
348 public override bool CanSeek {
354 public virtual bool IsAsync {
366 public override long Length {
368 if (safeHandle.IsClosed)
369 throw new ObjectDisposedException ("Stream has been closed");
372 throw new NotSupportedException ("The stream does not support seeking");
374 // Buffered data might change the length of the stream
375 FlushBufferIfDirty ();
379 long length = MonoIO.GetLength (safeHandle, out error);
381 if (error != MonoIOError.ERROR_SUCCESS) {
382 // don't leak the path information for isolated storage
383 throw MonoIO.GetException (GetSecureFileName (name), error);
390 public override long Position {
392 if (safeHandle.IsClosed)
393 throw new ObjectDisposedException ("Stream has been closed");
395 if (CanSeek == false)
396 throw new NotSupportedException("The stream does not support seeking");
399 return(buf_start + buf_offset);
401 // If the handle was leaked outside we always ask the real handle
404 long ret = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
406 if (error != MonoIOError.ERROR_SUCCESS) {
407 // don't leak the path information for isolated storage
408 throw MonoIO.GetException (GetSecureFileName (name), error);
414 if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
416 Seek (value, SeekOrigin.Begin);
420 [Obsolete ("Use SafeFileHandle instead")]
421 public virtual IntPtr Handle {
422 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
423 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
425 var handle = safeHandle.DangerousGetHandle ();
432 public virtual SafeFileHandle SafeFileHandle {
433 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
434 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
446 InitBuffer (0, true);
451 public override int ReadByte ()
453 if (safeHandle.IsClosed)
454 throw new ObjectDisposedException ("Stream has been closed");
457 throw new NotSupportedException ("Stream does not support reading");
460 int n = ReadData (safeHandle, buf, 0, 1);
461 if (n == 0) return -1;
464 else if (buf_offset >= buf_length) {
471 return buf [buf_offset ++];
474 public override void WriteByte (byte value)
476 if (safeHandle.IsClosed)
477 throw new ObjectDisposedException ("Stream has been closed");
480 throw new NotSupportedException ("Stream does not support writing");
482 if (buf_offset == buf_size)
485 if (buf_size == 0) { // No buffering
493 buf [buf_offset ++] = value;
494 if (buf_offset > buf_length)
495 buf_length = buf_offset;
500 public override int Read ([In,Out] byte[] array, int offset, int count)
502 if (safeHandle.IsClosed)
503 throw new ObjectDisposedException ("Stream has been closed");
505 throw new ArgumentNullException ("array");
507 throw new NotSupportedException ("Stream does not support reading");
508 int len = array.Length;
510 throw new ArgumentOutOfRangeException ("offset", "< 0");
512 throw new ArgumentOutOfRangeException ("count", "< 0");
514 throw new ArgumentException ("destination offset is beyond array size");
515 // reordered to avoid possible integer overflow
516 if (offset > len - count)
517 throw new ArgumentException ("Reading would overrun buffer");
520 IAsyncResult ares = BeginRead (array, offset, count, null, null);
521 return EndRead (ares);
524 return ReadInternal (array, offset, count);
527 int ReadInternal (byte [] dest, int offset, int count)
529 int n = ReadSegment (dest, offset, count);
537 if (count > buf_size) {
538 /* Read as much as we can, up
542 n = ReadData (safeHandle, dest, offset+n, count);
544 /* Make the next buffer read
545 * start from the right place
550 n = ReadSegment (dest, offset+copied, count);
556 delegate int ReadDelegate (byte [] buffer, int offset, int count);
558 public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes,
559 AsyncCallback userCallback, object stateObject)
561 if (safeHandle.IsClosed)
562 throw new ObjectDisposedException ("Stream has been closed");
565 throw new NotSupportedException ("This stream does not support reading");
568 throw new ArgumentNullException ("array");
571 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
574 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
576 // reordered to avoid possible integer overflow
577 if (numBytes > array.Length - offset)
578 throw new ArgumentException ("Buffer too small. numBytes/offset wrong.");
581 return base.BeginRead (array, offset, numBytes, userCallback, stateObject);
583 ReadDelegate r = new ReadDelegate (ReadInternal);
584 return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
587 public override int EndRead (IAsyncResult asyncResult)
589 if (asyncResult == null)
590 throw new ArgumentNullException ("asyncResult");
593 return base.EndRead (asyncResult);
595 AsyncResult ares = asyncResult as AsyncResult;
597 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
599 ReadDelegate r = ares.AsyncDelegate as ReadDelegate;
601 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
603 return r.EndInvoke (asyncResult);
606 public override void Write (byte[] array, int offset, int count)
608 if (safeHandle.IsClosed)
609 throw new ObjectDisposedException ("Stream has been closed");
611 throw new ArgumentNullException ("array");
613 throw new ArgumentOutOfRangeException ("offset", "< 0");
615 throw new ArgumentOutOfRangeException ("count", "< 0");
616 // ordered to avoid possible integer overflow
617 if (offset > array.Length - count)
618 throw new ArgumentException ("Reading would overrun buffer");
620 throw new NotSupportedException ("Stream does not support writing");
623 IAsyncResult ares = BeginWrite (array, offset, count, null, null);
628 WriteInternal (array, offset, count);
631 void WriteInternal (byte [] src, int offset, int count)
633 if (count > buf_size) {
634 // shortcut for long writes
641 int n = MonoIO.Write (safeHandle, src, offset, wcount, out error);
642 if (error != MonoIOError.ERROR_SUCCESS)
643 throw MonoIO.GetException (GetSecureFileName (name), error);
654 int n = WriteSegment (src, offset + copied, count);
667 delegate void WriteDelegate (byte [] buffer, int offset, int count);
669 public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
670 AsyncCallback userCallback, object stateObject)
672 if (safeHandle.IsClosed)
673 throw new ObjectDisposedException ("Stream has been closed");
676 throw new NotSupportedException ("This stream does not support writing");
679 throw new ArgumentNullException ("array");
682 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
685 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
687 // reordered to avoid possible integer overflow
688 if (numBytes > array.Length - offset)
689 throw new ArgumentException ("array too small. numBytes/offset wrong.");
692 return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
694 FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
695 result.BytesRead = -1;
696 result.Count = numBytes;
697 result.OriginalCount = numBytes;
700 MemoryStream ms = new MemoryStream ();
702 ms.Write (array, offset, numBytes);
704 // Set arguments to new compounded buffer
706 array = ms.ToArray ();
707 numBytes = array.Length;
710 WriteDelegate w = WriteInternal;
711 return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
714 public override void EndWrite (IAsyncResult asyncResult)
716 if (asyncResult == null)
717 throw new ArgumentNullException ("asyncResult");
720 base.EndWrite (asyncResult);
724 AsyncResult ares = asyncResult as AsyncResult;
726 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
728 WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
730 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
732 w.EndInvoke (asyncResult);
736 public override long Seek (long offset, SeekOrigin origin)
740 if (safeHandle.IsClosed)
741 throw new ObjectDisposedException ("Stream has been closed");
745 if(CanSeek == false) {
746 throw new NotSupportedException("The stream does not support seeking");
751 pos = Length + offset;
754 case SeekOrigin.Current:
755 pos = Position + offset;
758 case SeekOrigin.Begin:
763 throw new ArgumentException ("origin", "Invalid SeekOrigin");
767 /* LAMESPEC: shouldn't this be
768 * ArgumentOutOfRangeException?
770 throw new IOException("Attempted to Seek before the beginning of the stream");
773 if(pos < this.append_startpos) {
774 /* More undocumented crap */
775 throw new IOException("Can't seek back over pre-existing data in append mode");
782 buf_start = MonoIO.Seek (safeHandle, pos, SeekOrigin.Begin, out error);
784 if (error != MonoIOError.ERROR_SUCCESS) {
785 // don't leak the path information for isolated storage
786 throw MonoIO.GetException (GetSecureFileName (name), error);
792 public override void SetLength (long value)
794 if (safeHandle.IsClosed)
795 throw new ObjectDisposedException ("Stream has been closed");
798 throw new NotSupportedException("The stream does not support seeking");
800 if(CanWrite == false)
801 throw new NotSupportedException("The stream does not support writing");
804 throw new ArgumentOutOfRangeException("value is less than 0");
810 MonoIO.SetLength (safeHandle, value, out error);
811 if (error != MonoIOError.ERROR_SUCCESS) {
812 // don't leak the path information for isolated storage
813 throw MonoIO.GetException (GetSecureFileName (name), error);
816 if (Position > value)
820 public override void Flush ()
822 if (safeHandle.IsClosed)
823 throw new ObjectDisposedException ("Stream has been closed");
828 public virtual void Flush (bool flushToDisk)
830 if (safeHandle.IsClosed)
831 throw new ObjectDisposedException ("Stream has been closed");
835 // This does the fsync
838 MonoIO.Flush (safeHandle, out error);
842 public virtual void Lock (long position, long length)
844 if (safeHandle.IsClosed)
845 throw new ObjectDisposedException ("Stream has been closed");
847 throw new ArgumentOutOfRangeException ("position must not be negative");
850 throw new ArgumentOutOfRangeException ("length must not be negative");
855 MonoIO.Lock (safeHandle, position, length, out error);
856 if (error != MonoIOError.ERROR_SUCCESS) {
857 // don't leak the path information for isolated storage
858 throw MonoIO.GetException (GetSecureFileName (name), error);
862 public virtual void Unlock (long position, long length)
864 if (safeHandle.IsClosed)
865 throw new ObjectDisposedException ("Stream has been closed");
867 throw new ArgumentOutOfRangeException ("position must not be negative");
870 throw new ArgumentOutOfRangeException ("length must not be negative");
875 MonoIO.Unlock (safeHandle, position, length, out error);
876 if (error != MonoIOError.ERROR_SUCCESS) {
877 // don't leak the path information for isolated storage
878 throw MonoIO.GetException (GetSecureFileName (name), error);
889 protected override void Dispose (bool disposing)
891 Exception exc = null;
892 if (safeHandle != null && !safeHandle.IsClosed) {
894 // If the FileStream is in "exposed" status
895 // it means that we do not have a buffer(we write the data without buffering)
896 // therefor we don't and can't flush the buffer becouse we don't have one.
898 } catch (Exception e) {
905 MonoIO.Close (safeHandle.DangerousGetHandle (), out error);
906 if (error != MonoIOError.ERROR_SUCCESS) {
907 // don't leak the path information for isolated storage
908 throw MonoIO.GetException (GetSecureFileName (name), error);
911 safeHandle.DangerousRelease ();
918 if (disposing && buf != null) {
919 if (buf.Length == DefaultBufferSize && buf_recycle == null) {
920 lock (buf_recycle_lock) {
921 if (buf_recycle == null) {
928 GC.SuppressFinalize (this);
935 public FileSecurity GetAccessControl ()
937 if (safeHandle.IsClosed)
938 throw new ObjectDisposedException ("Stream has been closed");
940 return new FileSecurity (SafeFileHandle,
941 AccessControlSections.Owner |
942 AccessControlSections.Group |
943 AccessControlSections.Access);
946 public void SetAccessControl (FileSecurity fileSecurity)
948 if (safeHandle.IsClosed)
949 throw new ObjectDisposedException ("Stream has been closed");
951 if (null == fileSecurity)
952 throw new ArgumentNullException ("fileSecurity");
954 fileSecurity.PersistModifications (SafeFileHandle);
958 public override Task FlushAsync (CancellationToken cancellationToken)
960 if (safeHandle.IsClosed)
961 throw new ObjectDisposedException ("Stream has been closed");
963 return base.FlushAsync (cancellationToken);
966 public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
968 return base.ReadAsync (buffer, offset, count, cancellationToken);
971 public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
973 return base.WriteAsync (buffer, offset, count, cancellationToken);
978 // ReadSegment, WriteSegment, FlushBuffer,
979 // RefillBuffer and ReadData should only be called
980 // when the Monitor lock is held, but these methods
981 // grab it again just to be safe.
983 private int ReadSegment (byte [] dest, int dest_offset, int count)
985 count = Math.Min (count, buf_length - buf_offset);
988 // Use the fastest method, all range checks has been done
989 Buffer.InternalBlockCopy (buf, buf_offset, dest, dest_offset, count);
996 private int WriteSegment (byte [] src, int src_offset,
999 if (count > buf_size - buf_offset) {
1000 count = buf_size - buf_offset;
1004 Buffer.BlockCopy (src, src_offset,
1007 buf_offset += count;
1008 if (buf_offset > buf_length) {
1009 buf_length = buf_offset;
1021 // if (st == null) {
1024 if (CanSeek == true && !isExposed) {
1025 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
1027 if (error != MonoIOError.ERROR_SUCCESS) {
1028 // don't leak the path information for isolated storage
1029 throw MonoIO.GetException (GetSecureFileName (name), error);
1033 int wcount = buf_length;
1036 int n = MonoIO.Write (safeHandle, buf, 0, buf_length, out error);
1037 if (error != MonoIOError.ERROR_SUCCESS) {
1038 // don't leak the path information for isolated storage
1039 throw MonoIO.GetException (GetSecureFileName (name), error);
1045 // st.Write (buf, 0, buf_length);
1049 buf_start += buf_offset;
1050 buf_offset = buf_length = 0;
1054 private void FlushBufferIfDirty ()
1060 private void RefillBuffer ()
1064 buf_length = ReadData (safeHandle, buf, 0, buf_size);
1067 private int ReadData (SafeHandle safeHandle, byte[] buf, int offset,
1073 /* when async == true, if we get here we don't suport AIO or it's disabled
1074 * and we're using the threadpool */
1075 amount = MonoIO.Read (safeHandle, buf, offset, count, out error);
1076 if (error == MonoIOError.ERROR_BROKEN_PIPE) {
1077 amount = 0; // might not be needed, but well...
1078 } else if (error != MonoIOError.ERROR_SUCCESS) {
1079 // don't leak the path information for isolated storage
1080 throw MonoIO.GetException (GetSecureFileName (name), error);
1083 /* Check for read error */
1085 throw new IOException ();
1091 void InitBuffer (int size, bool isZeroSize)
1098 throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
1100 size = Math.Max (size, 8);
1103 // Instead of allocating a new default buffer use the
1104 // last one if there is any available
1106 if (size <= DefaultBufferSize && buf_recycle != null) {
1107 lock (buf_recycle_lock) {
1108 if (buf_recycle != null) {
1116 buf = new byte [size];
1118 Array.Clear (buf, 0, size);
1123 // buf_offset = buf_length = 0;
1124 // buf_dirty = false;
1127 private string GetSecureFileName (string filename)
1129 return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
1132 private string GetSecureFileName (string filename, bool full)
1134 return (anonymous) ? Path.GetFileName (filename) :
1135 (full) ? Path.GetFullPath (filename) : filename;
1140 internal const int DefaultBufferSize = 4096;
1142 // Input buffer ready for recycling
1143 static byte[] buf_recycle;
1144 static readonly object buf_recycle_lock = new object ();
1146 private byte [] buf; // the buffer
1147 private string name = "[Unknown]"; // name of file.
1149 private SafeFileHandle safeHandle;
1150 private bool isExposed;
1152 private long append_startpos;
1154 private FileAccess access;
1157 private bool canseek;
1158 private bool anonymous;
1159 private bool buf_dirty; // true if buffer has been written to
1161 private int buf_size; // capacity in bytes
1162 private int buf_length; // number of valid bytes in buffer
1163 private int buf_offset; // position of next byte
1164 private long buf_start; // location of buffer in file