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.AccessControl;
41 using System.Security.Permissions;
42 using System.Threading;
43 using System.Threading.Tasks;
44 using Microsoft.Win32.SafeHandles;
49 public class FileStream : Stream
51 // construct from handle
53 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
54 public FileStream (IntPtr handle, FileAccess access)
55 : this (handle, access, true, DefaultBufferSize, false, false) {}
57 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
58 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle)
59 : this (handle, access, ownsHandle, DefaultBufferSize, false, false) {}
61 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")]
62 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
63 : this (handle, access, ownsHandle, bufferSize, false, false) {}
65 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")]
66 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
67 : this (handle, access, ownsHandle, bufferSize, isAsync, false) {}
69 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
70 internal FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isConsoleWrapper)
72 if (handle == MonoIO.InvalidHandle)
73 throw new ArgumentException ("handle", Locale.GetText ("Invalid."));
75 Init (new SafeFileHandle (handle, false), access, ownsHandle, bufferSize, isAsync, isConsoleWrapper);
78 // construct from filename
80 public FileStream (string path, FileMode mode)
81 : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.Read, DefaultBufferSize, false, FileOptions.None)
85 public FileStream (string path, FileMode mode, FileAccess access)
86 : this (path, mode, access, access == FileAccess.Write ? FileShare.None : FileShare.Read, DefaultBufferSize, false, false)
90 public FileStream (string path, FileMode mode, FileAccess access, FileShare share)
91 : this (path, mode, access, share, DefaultBufferSize, false, FileOptions.None)
95 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
96 : this (path, mode, access, share, bufferSize, false, FileOptions.None)
100 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
101 : this (path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
105 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
106 : this (path, mode, access, share, bufferSize, false, options)
110 public FileStream (SafeFileHandle handle, FileAccess access)
111 :this(handle, access, DefaultBufferSize, false)
115 public FileStream (SafeFileHandle handle, FileAccess access,
117 :this(handle, access, bufferSize, false)
121 public FileStream (SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
123 Init (handle, access, false, bufferSize, isAsync, false);
126 [MonoLimitation ("This ignores the rights parameter")]
127 public FileStream (string path, FileMode mode,
128 FileSystemRights rights, FileShare share,
129 int bufferSize, FileOptions options)
130 : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
134 [MonoLimitation ("This ignores the rights and fileSecurity parameters")]
135 public FileStream (string path, FileMode mode,
136 FileSystemRights rights, FileShare share,
137 int bufferSize, FileOptions options,
138 FileSecurity fileSecurity)
139 : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
143 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath = false, bool checkHost = false)
144 : this (path, mode, access, share, bufferSize, false, options)
148 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool isAsync, bool anonymous)
149 : this (path, mode, access, share, bufferSize, anonymous, isAsync ? FileOptions.Asynchronous : FileOptions.None)
153 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool anonymous, FileOptions options)
156 throw new ArgumentNullException ("path");
159 if (path.Length == 0) {
160 throw new ArgumentException ("Path is empty");
163 this.anonymous = anonymous;
164 // ignore the Inheritable flag
165 share &= ~FileShare.Inheritable;
168 throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
170 if (mode < FileMode.CreateNew || mode > FileMode.Append) {
173 throw new ArgumentException ("mode", "Enum value was out of legal range.");
176 throw new ArgumentOutOfRangeException ("mode", "Enum value was out of legal range.");
179 if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
180 throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
183 if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
184 throw new ArgumentOutOfRangeException ("share", "Enum value was out of legal range.");
187 if (path.IndexOfAny (Path.InvalidPathChars) != -1) {
188 throw new ArgumentException ("Name has invalid chars");
191 path = Path.InsecureGetFullPath (path);
193 if (Directory.Exists (path)) {
194 // don't leak the path information for isolated storage
195 string msg = Locale.GetText ("Access to the path '{0}' is denied.");
196 throw new UnauthorizedAccessException (String.Format (msg, GetSecureFileName (path, false)));
199 /* Append streams can't be read (see FileMode
202 if (mode==FileMode.Append &&
203 (access&FileAccess.Read)==FileAccess.Read) {
204 throw new ArgumentException("Append access can be requested only in write-only mode.");
207 if ((access & FileAccess.Write) == 0 &&
208 (mode != FileMode.Open && mode != FileMode.OpenOrCreate)) {
209 string msg = Locale.GetText ("Combining FileMode: {0} with " +
210 "FileAccess: {1} is invalid.");
211 throw new ArgumentException (string.Format (msg, access, mode));
214 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
216 string dname = Path.GetDirectoryName (path);
217 if (dname.Length > 0) {
218 string fp = Path.GetFullPath (dname);
219 if (!Directory.Exists (fp)) {
220 // don't leak the path information for isolated storage
221 string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
222 string fname = (anonymous) ? dname : Path.GetFullPath (path);
223 throw new DirectoryNotFoundException (String.Format (msg, fname));
227 if (access == FileAccess.Read && mode != FileMode.Create && mode != FileMode.OpenOrCreate &&
228 mode != FileMode.CreateNew && !File.Exists (path)) {
229 // don't leak the path information for isolated storage
230 string msg = Locale.GetText ("Could not find file \"{0}\".");
231 string fname = GetSecureFileName (path);
232 throw new FileNotFoundException (String.Format (msg, fname), fname);
235 // IsolatedStorage needs to keep the Name property to the default "[Unknown]"
239 // TODO: demand permissions
243 var nativeHandle = MonoIO.Open (path, mode, access, share, options, out error);
245 if (nativeHandle == MonoIO.InvalidHandle) {
246 // don't leak the path information for isolated storage
247 throw MonoIO.GetException (GetSecureFileName (path), error);
250 this.safeHandle = new SafeFileHandle (nativeHandle, false);
252 this.access = access;
255 /* Can we open non-files by name? */
257 if (MonoIO.GetFileType (safeHandle, out error) == MonoFileType.Disk) {
259 this.async = (options & FileOptions.Asynchronous) != 0;
261 this.canseek = false;
266 if (access == FileAccess.Read && canseek && (bufferSize == DefaultBufferSize)) {
267 /* Avoid allocating a large buffer for small files */
269 if (bufferSize > len) {
270 bufferSize = (int)(len < 1000 ? 1000 : len);
274 InitBuffer (bufferSize, false);
276 if (mode==FileMode.Append) {
277 this.Seek (0, SeekOrigin.End);
278 this.append_startpos=this.Position;
280 this.append_startpos=0;
284 private void Init (SafeFileHandle safeHandle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isConsoleWrapper)
286 if (!isConsoleWrapper && safeHandle.IsInvalid)
287 throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
288 if (access < FileAccess.Read || access > FileAccess.ReadWrite)
289 throw new ArgumentOutOfRangeException ("access");
290 if (!isConsoleWrapper && bufferSize <= 0)
291 throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
294 MonoFileType ftype = MonoIO.GetFileType (safeHandle, out error);
296 if (error != MonoIOError.ERROR_SUCCESS) {
297 throw MonoIO.GetException (name, error);
300 if (ftype == MonoFileType.Unknown) {
301 throw new IOException ("Invalid handle.");
302 } else if (ftype == MonoFileType.Disk) {
305 this.canseek = false;
308 this.safeHandle = safeHandle;
310 this.access = access;
311 this.owner = ownsHandle;
312 this.async = isAsync;
313 this.anonymous = false;
316 buf_start = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
317 if (error != MonoIOError.ERROR_SUCCESS) {
318 throw MonoIO.GetException (name, error);
322 /* Can't set append mode */
323 this.append_startpos=0;
328 public override bool CanRead {
330 return access == FileAccess.Read ||
331 access == FileAccess.ReadWrite;
335 public override bool CanWrite {
337 return access == FileAccess.Write ||
338 access == FileAccess.ReadWrite;
342 public override bool CanSeek {
348 public virtual bool IsAsync {
360 public override long Length {
362 if (safeHandle.IsClosed)
363 throw new ObjectDisposedException ("Stream has been closed");
366 throw new NotSupportedException ("The stream does not support seeking");
368 // Buffered data might change the length of the stream
369 FlushBufferIfDirty ();
373 long length = MonoIO.GetLength (safeHandle, out error);
375 if (error != MonoIOError.ERROR_SUCCESS) {
376 // don't leak the path information for isolated storage
377 throw MonoIO.GetException (GetSecureFileName (name), error);
384 public override long Position {
386 if (safeHandle.IsClosed)
387 throw new ObjectDisposedException ("Stream has been closed");
389 if (CanSeek == false)
390 throw new NotSupportedException("The stream does not support seeking");
393 return(buf_start + buf_offset);
395 // If the handle was leaked outside we always ask the real handle
398 long ret = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
400 if (error != MonoIOError.ERROR_SUCCESS) {
401 // don't leak the path information for isolated storage
402 throw MonoIO.GetException (GetSecureFileName (name), error);
408 if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
410 Seek (value, SeekOrigin.Begin);
414 [Obsolete ("Use SafeFileHandle instead")]
415 public virtual IntPtr Handle {
416 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
417 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
419 var handle = safeHandle.DangerousGetHandle ();
426 public virtual SafeFileHandle SafeFileHandle {
427 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
428 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
440 InitBuffer (0, true);
445 public override int ReadByte ()
447 if (safeHandle.IsClosed)
448 throw new ObjectDisposedException ("Stream has been closed");
451 throw new NotSupportedException ("Stream does not support reading");
454 int n = ReadData (safeHandle, buf, 0, 1);
455 if (n == 0) return -1;
458 else if (buf_offset >= buf_length) {
465 return buf [buf_offset ++];
468 public override void WriteByte (byte value)
470 if (safeHandle.IsClosed)
471 throw new ObjectDisposedException ("Stream has been closed");
474 throw new NotSupportedException ("Stream does not support writing");
476 if (buf_offset == buf_size)
479 if (buf_size == 0) { // No buffering
487 buf [buf_offset ++] = value;
488 if (buf_offset > buf_length)
489 buf_length = buf_offset;
494 public override int Read ([In,Out] byte[] array, int offset, int count)
496 if (safeHandle.IsClosed)
497 throw new ObjectDisposedException ("Stream has been closed");
499 throw new ArgumentNullException ("array");
501 throw new NotSupportedException ("Stream does not support reading");
502 int len = array.Length;
504 throw new ArgumentOutOfRangeException ("offset", "< 0");
506 throw new ArgumentOutOfRangeException ("count", "< 0");
508 throw new ArgumentException ("destination offset is beyond array size");
509 // reordered to avoid possible integer overflow
510 if (offset > len - count)
511 throw new ArgumentException ("Reading would overrun buffer");
514 IAsyncResult ares = BeginRead (array, offset, count, null, null);
515 return EndRead (ares);
518 return ReadInternal (array, offset, count);
521 int ReadInternal (byte [] dest, int offset, int count)
523 int n = ReadSegment (dest, offset, count);
531 if (count > buf_size) {
532 /* Read as much as we can, up
536 n = ReadData (safeHandle, dest, offset+n, count);
538 /* Make the next buffer read
539 * start from the right place
544 n = ReadSegment (dest, offset+copied, count);
550 delegate int ReadDelegate (byte [] buffer, int offset, int count);
552 public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes,
553 AsyncCallback userCallback, object stateObject)
555 if (safeHandle.IsClosed)
556 throw new ObjectDisposedException ("Stream has been closed");
559 throw new NotSupportedException ("This stream does not support reading");
562 throw new ArgumentNullException ("array");
565 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
568 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
570 // reordered to avoid possible integer overflow
571 if (numBytes > array.Length - offset)
572 throw new ArgumentException ("Buffer too small. numBytes/offset wrong.");
575 return base.BeginRead (array, offset, numBytes, userCallback, stateObject);
577 ReadDelegate r = new ReadDelegate (ReadInternal);
578 return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
581 public override int EndRead (IAsyncResult asyncResult)
583 if (asyncResult == null)
584 throw new ArgumentNullException ("asyncResult");
587 return base.EndRead (asyncResult);
589 AsyncResult ares = asyncResult as AsyncResult;
591 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
593 ReadDelegate r = ares.AsyncDelegate as ReadDelegate;
595 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
597 return r.EndInvoke (asyncResult);
600 public override void Write (byte[] array, int offset, int count)
602 if (safeHandle.IsClosed)
603 throw new ObjectDisposedException ("Stream has been closed");
605 throw new ArgumentNullException ("array");
607 throw new ArgumentOutOfRangeException ("offset", "< 0");
609 throw new ArgumentOutOfRangeException ("count", "< 0");
610 // ordered to avoid possible integer overflow
611 if (offset > array.Length - count)
612 throw new ArgumentException ("Reading would overrun buffer");
614 throw new NotSupportedException ("Stream does not support writing");
617 IAsyncResult ares = BeginWrite (array, offset, count, null, null);
622 WriteInternal (array, offset, count);
625 void WriteInternal (byte [] src, int offset, int count)
627 if (count > buf_size) {
628 // shortcut for long writes
633 if (CanSeek && !isExposed) {
634 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
635 if (error != MonoIOError.ERROR_SUCCESS)
636 throw MonoIO.GetException (GetSecureFileName (name), error);
642 int n = MonoIO.Write (safeHandle, src, offset, wcount, out error);
643 if (error != MonoIOError.ERROR_SUCCESS)
644 throw MonoIO.GetException (GetSecureFileName (name), error);
655 int n = WriteSegment (src, offset + copied, count);
668 delegate void WriteDelegate (byte [] buffer, int offset, int count);
670 public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
671 AsyncCallback userCallback, object stateObject)
673 if (safeHandle.IsClosed)
674 throw new ObjectDisposedException ("Stream has been closed");
677 throw new NotSupportedException ("This stream does not support writing");
680 throw new ArgumentNullException ("array");
683 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
686 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
688 // reordered to avoid possible integer overflow
689 if (numBytes > array.Length - offset)
690 throw new ArgumentException ("array too small. numBytes/offset wrong.");
693 return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
695 FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
696 result.BytesRead = -1;
697 result.Count = numBytes;
698 result.OriginalCount = numBytes;
701 MemoryStream ms = new MemoryStream ();
703 ms.Write (array, offset, numBytes);
705 // Set arguments to new compounded buffer
707 array = ms.ToArray ();
708 numBytes = array.Length;
711 WriteDelegate w = WriteInternal;
712 return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
715 public override void EndWrite (IAsyncResult asyncResult)
717 if (asyncResult == null)
718 throw new ArgumentNullException ("asyncResult");
721 base.EndWrite (asyncResult);
725 AsyncResult ares = asyncResult as AsyncResult;
727 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
729 WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
731 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
733 w.EndInvoke (asyncResult);
737 public override long Seek (long offset, SeekOrigin origin)
741 if (safeHandle.IsClosed)
742 throw new ObjectDisposedException ("Stream has been closed");
746 if(CanSeek == false) {
747 throw new NotSupportedException("The stream does not support seeking");
752 pos = Length + offset;
755 case SeekOrigin.Current:
756 pos = Position + offset;
759 case SeekOrigin.Begin:
764 throw new ArgumentException ("origin", "Invalid SeekOrigin");
768 /* LAMESPEC: shouldn't this be
769 * ArgumentOutOfRangeException?
771 throw new IOException("Attempted to Seek before the beginning of the stream");
774 if(pos < this.append_startpos) {
775 /* More undocumented crap */
776 throw new IOException("Can't seek back over pre-existing data in append mode");
783 buf_start = MonoIO.Seek (safeHandle, pos, SeekOrigin.Begin, out error);
785 if (error != MonoIOError.ERROR_SUCCESS) {
786 // don't leak the path information for isolated storage
787 throw MonoIO.GetException (GetSecureFileName (name), error);
793 public override void SetLength (long value)
795 if (safeHandle.IsClosed)
796 throw new ObjectDisposedException ("Stream has been closed");
799 throw new NotSupportedException("The stream does not support seeking");
801 if(CanWrite == false)
802 throw new NotSupportedException("The stream does not support writing");
805 throw new ArgumentOutOfRangeException("value is less than 0");
811 MonoIO.SetLength (safeHandle, value, out error);
812 if (error != MonoIOError.ERROR_SUCCESS) {
813 // don't leak the path information for isolated storage
814 throw MonoIO.GetException (GetSecureFileName (name), error);
817 if (Position > value)
821 public override void Flush ()
823 if (safeHandle.IsClosed)
824 throw new ObjectDisposedException ("Stream has been closed");
829 public virtual void Flush (bool flushToDisk)
831 if (safeHandle.IsClosed)
832 throw new ObjectDisposedException ("Stream has been closed");
836 // This does the fsync
839 MonoIO.Flush (safeHandle, out error);
843 public virtual void Lock (long position, long length)
845 if (safeHandle.IsClosed)
846 throw new ObjectDisposedException ("Stream has been closed");
848 throw new ArgumentOutOfRangeException ("position must not be negative");
851 throw new ArgumentOutOfRangeException ("length must not be negative");
856 MonoIO.Lock (safeHandle, position, length, out error);
857 if (error != MonoIOError.ERROR_SUCCESS) {
858 // don't leak the path information for isolated storage
859 throw MonoIO.GetException (GetSecureFileName (name), error);
863 public virtual void Unlock (long position, long length)
865 if (safeHandle.IsClosed)
866 throw new ObjectDisposedException ("Stream has been closed");
868 throw new ArgumentOutOfRangeException ("position must not be negative");
871 throw new ArgumentOutOfRangeException ("length must not be negative");
876 MonoIO.Unlock (safeHandle, position, length, out error);
877 if (error != MonoIOError.ERROR_SUCCESS) {
878 // don't leak the path information for isolated storage
879 throw MonoIO.GetException (GetSecureFileName (name), error);
890 protected override void Dispose (bool disposing)
892 Exception exc = null;
893 if (safeHandle != null && !safeHandle.IsClosed) {
895 // If the FileStream is in "exposed" status
896 // it means that we do not have a buffer(we write the data without buffering)
897 // therefor we don't and can't flush the buffer becouse we don't have one.
899 } catch (Exception e) {
906 MonoIO.Close (safeHandle.DangerousGetHandle (), out error);
907 if (error != MonoIOError.ERROR_SUCCESS) {
908 // don't leak the path information for isolated storage
909 throw MonoIO.GetException (GetSecureFileName (name), error);
912 safeHandle.DangerousRelease ();
919 if (disposing && buf != null) {
920 if (buf.Length == DefaultBufferSize && buf_recycle == null) {
921 lock (buf_recycle_lock) {
922 if (buf_recycle == null) {
929 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);
957 public override Task FlushAsync (CancellationToken cancellationToken)
959 if (safeHandle.IsClosed)
960 throw new ObjectDisposedException ("Stream has been closed");
962 return base.FlushAsync (cancellationToken);
965 public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
967 return base.ReadAsync (buffer, offset, count, cancellationToken);
970 public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
972 return base.WriteAsync (buffer, offset, count, cancellationToken);
977 // ReadSegment, WriteSegment, FlushBuffer,
978 // RefillBuffer and ReadData should only be called
979 // when the Monitor lock is held, but these methods
980 // grab it again just to be safe.
982 private int ReadSegment (byte [] dest, int dest_offset, int count)
984 count = Math.Min (count, buf_length - buf_offset);
987 // Use the fastest method, all range checks has been done
988 Buffer.InternalBlockCopy (buf, buf_offset, dest, dest_offset, count);
995 private int WriteSegment (byte [] src, int src_offset,
998 if (count > buf_size - buf_offset) {
999 count = buf_size - buf_offset;
1003 Buffer.BlockCopy (src, src_offset,
1006 buf_offset += count;
1007 if (buf_offset > buf_length) {
1008 buf_length = buf_offset;
1020 // if (st == null) {
1023 if (CanSeek == true && !isExposed) {
1024 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
1026 if (error != MonoIOError.ERROR_SUCCESS) {
1027 // don't leak the path information for isolated storage
1028 throw MonoIO.GetException (GetSecureFileName (name), error);
1032 int wcount = buf_length;
1035 int n = MonoIO.Write (safeHandle, buf, offset, buf_length, out error);
1036 if (error != MonoIOError.ERROR_SUCCESS) {
1037 // don't leak the path information for isolated storage
1038 throw MonoIO.GetException (GetSecureFileName (name), error);
1044 // st.Write (buf, 0, buf_length);
1048 buf_start += buf_offset;
1049 buf_offset = buf_length = 0;
1053 private void FlushBufferIfDirty ()
1059 private void RefillBuffer ()
1063 buf_length = ReadData (safeHandle, buf, 0, buf_size);
1066 private int ReadData (SafeHandle safeHandle, byte[] buf, int offset,
1072 /* when async == true, if we get here we don't suport AIO or it's disabled
1073 * and we're using the threadpool */
1074 amount = MonoIO.Read (safeHandle, buf, offset, count, out error);
1075 if (error == MonoIOError.ERROR_BROKEN_PIPE) {
1076 amount = 0; // might not be needed, but well...
1077 } else if (error != MonoIOError.ERROR_SUCCESS) {
1078 // don't leak the path information for isolated storage
1079 throw MonoIO.GetException (GetSecureFileName (name), error);
1082 /* Check for read error */
1084 throw new IOException ();
1090 void InitBuffer (int size, bool isZeroSize)
1097 throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
1099 size = Math.Max (size, 8);
1102 // Instead of allocating a new default buffer use the
1103 // last one if there is any available
1105 if (size <= DefaultBufferSize && buf_recycle != null) {
1106 lock (buf_recycle_lock) {
1107 if (buf_recycle != null) {
1115 buf = new byte [size];
1117 Array.Clear (buf, 0, size);
1122 // buf_offset = buf_length = 0;
1123 // buf_dirty = false;
1126 private string GetSecureFileName (string filename)
1128 return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
1131 private string GetSecureFileName (string filename, bool full)
1133 return (anonymous) ? Path.GetFileName (filename) :
1134 (full) ? Path.GetFullPath (filename) : filename;
1139 internal const int DefaultBufferSize = 4096;
1141 // Input buffer ready for recycling
1142 static byte[] buf_recycle;
1143 static readonly object buf_recycle_lock = new object ();
1145 private byte [] buf; // the buffer
1146 private string name = "[Unknown]"; // name of file.
1148 private SafeFileHandle safeHandle;
1149 private bool isExposed;
1151 private long append_startpos;
1153 private FileAccess access;
1156 private bool canseek;
1157 private bool anonymous;
1158 private bool buf_dirty; // true if buffer has been written to
1160 private int buf_size; // capacity in bytes
1161 private int buf_length; // number of valid bytes in buffer
1162 private int buf_offset; // position of next byte
1163 private long buf_start; // location of buffer in file