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, bool checkHost)
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);
415 throw new ArgumentOutOfRangeException("Attempt to set the position to a negative value");
418 Seek (value, SeekOrigin.Begin);
422 [Obsolete ("Use SafeFileHandle instead")]
423 public virtual IntPtr Handle {
424 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
425 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
427 var handle = safeHandle.DangerousGetHandle ();
434 public virtual SafeFileHandle SafeFileHandle {
435 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
436 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
448 InitBuffer (0, true);
453 public override int ReadByte ()
455 if (safeHandle.IsClosed)
456 throw new ObjectDisposedException ("Stream has been closed");
459 throw new NotSupportedException ("Stream does not support reading");
462 int n = ReadData (safeHandle, buf, 0, 1);
463 if (n == 0) return -1;
466 else if (buf_offset >= buf_length) {
473 return buf [buf_offset ++];
476 public override void WriteByte (byte value)
478 if (safeHandle.IsClosed)
479 throw new ObjectDisposedException ("Stream has been closed");
482 throw new NotSupportedException ("Stream does not support writing");
484 if (buf_offset == buf_size)
487 if (buf_size == 0) { // No buffering
495 buf [buf_offset ++] = value;
496 if (buf_offset > buf_length)
497 buf_length = buf_offset;
502 public override int Read ([In,Out] byte[] array, int offset, int count)
504 if (safeHandle.IsClosed)
505 throw new ObjectDisposedException ("Stream has been closed");
507 throw new ArgumentNullException ("array");
509 throw new NotSupportedException ("Stream does not support reading");
510 int len = array.Length;
512 throw new ArgumentOutOfRangeException ("offset", "< 0");
514 throw new ArgumentOutOfRangeException ("count", "< 0");
516 throw new ArgumentException ("destination offset is beyond array size");
517 // reordered to avoid possible integer overflow
518 if (offset > len - count)
519 throw new ArgumentException ("Reading would overrun buffer");
522 IAsyncResult ares = BeginRead (array, offset, count, null, null);
523 return EndRead (ares);
526 return ReadInternal (array, offset, count);
529 int ReadInternal (byte [] dest, int offset, int count)
531 int n = ReadSegment (dest, offset, count);
539 if (count > buf_size) {
540 /* Read as much as we can, up
544 n = ReadData (safeHandle, dest, offset+n, count);
546 /* Make the next buffer read
547 * start from the right place
552 n = ReadSegment (dest, offset+copied, count);
558 delegate int ReadDelegate (byte [] buffer, int offset, int count);
560 public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes,
561 AsyncCallback userCallback, object stateObject)
563 if (safeHandle.IsClosed)
564 throw new ObjectDisposedException ("Stream has been closed");
567 throw new NotSupportedException ("This stream does not support reading");
570 throw new ArgumentNullException ("array");
573 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
576 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
578 // reordered to avoid possible integer overflow
579 if (numBytes > array.Length - offset)
580 throw new ArgumentException ("Buffer too small. numBytes/offset wrong.");
583 return base.BeginRead (array, offset, numBytes, userCallback, stateObject);
585 ReadDelegate r = new ReadDelegate (ReadInternal);
586 return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
589 public override int EndRead (IAsyncResult asyncResult)
591 if (asyncResult == null)
592 throw new ArgumentNullException ("asyncResult");
595 return base.EndRead (asyncResult);
597 AsyncResult ares = asyncResult as AsyncResult;
599 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
601 ReadDelegate r = ares.AsyncDelegate as ReadDelegate;
603 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
605 return r.EndInvoke (asyncResult);
608 public override void Write (byte[] array, int offset, int count)
610 if (safeHandle.IsClosed)
611 throw new ObjectDisposedException ("Stream has been closed");
613 throw new ArgumentNullException ("array");
615 throw new ArgumentOutOfRangeException ("offset", "< 0");
617 throw new ArgumentOutOfRangeException ("count", "< 0");
618 // ordered to avoid possible integer overflow
619 if (offset > array.Length - count)
620 throw new ArgumentException ("Reading would overrun buffer");
622 throw new NotSupportedException ("Stream does not support writing");
625 IAsyncResult ares = BeginWrite (array, offset, count, null, null);
630 WriteInternal (array, offset, count);
633 void WriteInternal (byte [] src, int offset, int count)
635 if (count > buf_size) {
636 // shortcut for long writes
643 int n = MonoIO.Write (safeHandle, src, offset, wcount, out error);
644 if (error != MonoIOError.ERROR_SUCCESS)
645 throw MonoIO.GetException (GetSecureFileName (name), error);
656 int n = WriteSegment (src, offset + copied, count);
669 delegate void WriteDelegate (byte [] buffer, int offset, int count);
671 public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
672 AsyncCallback userCallback, object stateObject)
674 if (safeHandle.IsClosed)
675 throw new ObjectDisposedException ("Stream has been closed");
678 throw new NotSupportedException ("This stream does not support writing");
681 throw new ArgumentNullException ("array");
684 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
687 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
689 // reordered to avoid possible integer overflow
690 if (numBytes > array.Length - offset)
691 throw new ArgumentException ("array too small. numBytes/offset wrong.");
694 return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
696 FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
697 result.BytesRead = -1;
698 result.Count = numBytes;
699 result.OriginalCount = numBytes;
702 MemoryStream ms = new MemoryStream ();
704 ms.Write (array, offset, numBytes);
706 // Set arguments to new compounded buffer
708 array = ms.ToArray ();
709 numBytes = array.Length;
712 WriteDelegate w = WriteInternal;
713 return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
716 public override void EndWrite (IAsyncResult asyncResult)
718 if (asyncResult == null)
719 throw new ArgumentNullException ("asyncResult");
722 base.EndWrite (asyncResult);
726 AsyncResult ares = asyncResult as AsyncResult;
728 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
730 WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
732 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
734 w.EndInvoke (asyncResult);
738 public override long Seek (long offset, SeekOrigin origin)
742 if (safeHandle.IsClosed)
743 throw new ObjectDisposedException ("Stream has been closed");
747 if(CanSeek == false) {
748 throw new NotSupportedException("The stream does not support seeking");
753 pos = Length + offset;
756 case SeekOrigin.Current:
757 pos = Position + offset;
760 case SeekOrigin.Begin:
765 throw new ArgumentException ("origin", "Invalid SeekOrigin");
769 /* LAMESPEC: shouldn't this be
770 * ArgumentOutOfRangeException?
772 throw new IOException("Attempted to Seek before the beginning of the stream");
775 if(pos < this.append_startpos) {
776 /* More undocumented crap */
777 throw new IOException("Can't seek back over pre-existing data in append mode");
784 buf_start = MonoIO.Seek (safeHandle, pos, SeekOrigin.Begin, out error);
786 if (error != MonoIOError.ERROR_SUCCESS) {
787 // don't leak the path information for isolated storage
788 throw MonoIO.GetException (GetSecureFileName (name), error);
794 public override void SetLength (long value)
796 if (safeHandle.IsClosed)
797 throw new ObjectDisposedException ("Stream has been closed");
800 throw new NotSupportedException("The stream does not support seeking");
802 if(CanWrite == false)
803 throw new NotSupportedException("The stream does not support writing");
806 throw new ArgumentOutOfRangeException("value is less than 0");
812 MonoIO.SetLength (safeHandle, value, out error);
813 if (error != MonoIOError.ERROR_SUCCESS) {
814 // don't leak the path information for isolated storage
815 throw MonoIO.GetException (GetSecureFileName (name), error);
818 if (Position > value)
822 public override void Flush ()
824 if (safeHandle.IsClosed)
825 throw new ObjectDisposedException ("Stream has been closed");
830 public virtual void Flush (bool flushToDisk)
832 if (safeHandle.IsClosed)
833 throw new ObjectDisposedException ("Stream has been closed");
837 // This does the fsync
840 MonoIO.Flush (safeHandle, out error);
844 public virtual void Lock (long position, long length)
846 if (safeHandle.IsClosed)
847 throw new ObjectDisposedException ("Stream has been closed");
849 throw new ArgumentOutOfRangeException ("position must not be negative");
852 throw new ArgumentOutOfRangeException ("length must not be negative");
857 MonoIO.Lock (safeHandle, position, length, out error);
858 if (error != MonoIOError.ERROR_SUCCESS) {
859 // don't leak the path information for isolated storage
860 throw MonoIO.GetException (GetSecureFileName (name), error);
864 public virtual void Unlock (long position, long length)
866 if (safeHandle.IsClosed)
867 throw new ObjectDisposedException ("Stream has been closed");
869 throw new ArgumentOutOfRangeException ("position must not be negative");
872 throw new ArgumentOutOfRangeException ("length must not be negative");
877 MonoIO.Unlock (safeHandle, position, length, out error);
878 if (error != MonoIOError.ERROR_SUCCESS) {
879 // don't leak the path information for isolated storage
880 throw MonoIO.GetException (GetSecureFileName (name), error);
891 protected override void Dispose (bool disposing)
893 Exception exc = null;
894 if (safeHandle != null && !safeHandle.IsClosed) {
896 // If the FileStream is in "exposed" status
897 // it means that we do not have a buffer(we write the data without buffering)
898 // therefor we don't and can't flush the buffer becouse we don't have one.
900 } catch (Exception e) {
907 MonoIO.Close (safeHandle.DangerousGetHandle (), out error);
908 if (error != MonoIOError.ERROR_SUCCESS) {
909 // don't leak the path information for isolated storage
910 throw MonoIO.GetException (GetSecureFileName (name), error);
913 safeHandle.DangerousRelease ();
920 if (disposing && buf != null) {
921 if (buf.Length == DefaultBufferSize && buf_recycle == null) {
922 lock (buf_recycle_lock) {
923 if (buf_recycle == null) {
930 GC.SuppressFinalize (this);
937 public FileSecurity GetAccessControl ()
939 if (safeHandle.IsClosed)
940 throw new ObjectDisposedException ("Stream has been closed");
942 return new FileSecurity (SafeFileHandle,
943 AccessControlSections.Owner |
944 AccessControlSections.Group |
945 AccessControlSections.Access);
948 public void SetAccessControl (FileSecurity fileSecurity)
950 if (safeHandle.IsClosed)
951 throw new ObjectDisposedException ("Stream has been closed");
953 if (null == fileSecurity)
954 throw new ArgumentNullException ("fileSecurity");
956 fileSecurity.PersistModifications (SafeFileHandle);
960 public override Task FlushAsync (CancellationToken cancellationToken)
962 if (safeHandle.IsClosed)
963 throw new ObjectDisposedException ("Stream has been closed");
965 return base.FlushAsync (cancellationToken);
968 public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
970 return base.ReadAsync (buffer, offset, count, cancellationToken);
973 public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
975 return base.WriteAsync (buffer, offset, count, cancellationToken);
980 // ReadSegment, WriteSegment, FlushBuffer,
981 // RefillBuffer and ReadData should only be called
982 // when the Monitor lock is held, but these methods
983 // grab it again just to be safe.
985 private int ReadSegment (byte [] dest, int dest_offset, int count)
987 count = Math.Min (count, buf_length - buf_offset);
990 // Use the fastest method, all range checks has been done
991 Buffer.BlockCopyInternal (buf, buf_offset, dest, dest_offset, count);
998 private int WriteSegment (byte [] src, int src_offset,
1001 if (count > buf_size - buf_offset) {
1002 count = buf_size - buf_offset;
1006 Buffer.BlockCopy (src, src_offset,
1009 buf_offset += count;
1010 if (buf_offset > buf_length) {
1011 buf_length = buf_offset;
1023 // if (st == null) {
1026 if (CanSeek == true && !isExposed) {
1027 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
1029 if (error != MonoIOError.ERROR_SUCCESS) {
1030 // don't leak the path information for isolated storage
1031 throw MonoIO.GetException (GetSecureFileName (name), error);
1035 int wcount = buf_length;
1038 int n = MonoIO.Write (safeHandle, buf, 0, buf_length, out error);
1039 if (error != MonoIOError.ERROR_SUCCESS) {
1040 // don't leak the path information for isolated storage
1041 throw MonoIO.GetException (GetSecureFileName (name), error);
1047 // st.Write (buf, 0, buf_length);
1051 buf_start += buf_offset;
1052 buf_offset = buf_length = 0;
1056 private void FlushBufferIfDirty ()
1062 private void RefillBuffer ()
1066 buf_length = ReadData (safeHandle, buf, 0, buf_size);
1069 private int ReadData (SafeHandle safeHandle, byte[] buf, int offset,
1075 /* when async == true, if we get here we don't suport AIO or it's disabled
1076 * and we're using the threadpool */
1077 amount = MonoIO.Read (safeHandle, buf, offset, count, out error);
1078 if (error == MonoIOError.ERROR_BROKEN_PIPE) {
1079 amount = 0; // might not be needed, but well...
1080 } else if (error != MonoIOError.ERROR_SUCCESS) {
1081 // don't leak the path information for isolated storage
1082 throw MonoIO.GetException (GetSecureFileName (name), error);
1085 /* Check for read error */
1087 throw new IOException ();
1093 void InitBuffer (int size, bool isZeroSize)
1100 throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
1102 size = Math.Max (size, 8);
1105 // Instead of allocating a new default buffer use the
1106 // last one if there is any available
1108 if (size <= DefaultBufferSize && buf_recycle != null) {
1109 lock (buf_recycle_lock) {
1110 if (buf_recycle != null) {
1118 buf = new byte [size];
1120 Array.Clear (buf, 0, size);
1125 // buf_offset = buf_length = 0;
1126 // buf_dirty = false;
1129 private string GetSecureFileName (string filename)
1131 return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
1134 private string GetSecureFileName (string filename, bool full)
1136 return (anonymous) ? Path.GetFileName (filename) :
1137 (full) ? Path.GetFullPath (filename) : filename;
1142 internal const int DefaultBufferSize = 4096;
1144 // Input buffer ready for recycling
1145 static byte[] buf_recycle;
1146 static readonly object buf_recycle_lock = new object ();
1148 private byte [] buf; // the buffer
1149 private string name = "[Unknown]"; // name of file.
1151 private SafeFileHandle safeHandle;
1152 private bool isExposed;
1154 private long append_startpos;
1156 private FileAccess access;
1159 private bool canseek;
1160 private bool anonymous;
1161 private bool buf_dirty; // true if buffer has been written to
1163 private int buf_size; // capacity in bytes
1164 private int buf_length; // number of valid bytes in buffer
1165 private int buf_offset; // position of next byte
1166 private long buf_start; // location of buffer in file