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 isConsoleWrapper)
78 if (handle == MonoIO.InvalidHandle)
79 throw new ArgumentException ("handle", Locale.GetText ("Invalid."));
81 Init (new SafeFileHandle (handle, false), access, ownsHandle, bufferSize, isAsync, isConsoleWrapper);
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)
116 public FileStream (SafeFileHandle handle, FileAccess access)
117 :this(handle, access, DefaultBufferSize, false)
121 public FileStream (SafeFileHandle handle, FileAccess access,
123 :this(handle, access, bufferSize, false)
127 public FileStream (SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
129 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 isConsoleWrapper)
296 if (!isConsoleWrapper && safeHandle.IsInvalid)
297 throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
298 if (access < FileAccess.Read || access > FileAccess.ReadWrite)
299 throw new ArgumentOutOfRangeException ("access");
300 if (!isConsoleWrapper && bufferSize <= 0)
301 throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
304 MonoFileType ftype = MonoIO.GetFileType (safeHandle, out error);
306 if (error != MonoIOError.ERROR_SUCCESS) {
307 throw MonoIO.GetException (name, error);
310 if (ftype == MonoFileType.Unknown) {
311 throw new IOException ("Invalid handle.");
312 } else if (ftype == MonoFileType.Disk) {
315 this.canseek = false;
318 this.safeHandle = safeHandle;
320 this.access = access;
321 this.owner = ownsHandle;
322 this.async = isAsync;
323 this.anonymous = false;
326 buf_start = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
327 if (error != MonoIOError.ERROR_SUCCESS) {
328 throw MonoIO.GetException (name, error);
332 /* Can't set append mode */
333 this.append_startpos=0;
338 public override bool CanRead {
340 return access == FileAccess.Read ||
341 access == FileAccess.ReadWrite;
345 public override bool CanWrite {
347 return access == FileAccess.Write ||
348 access == FileAccess.ReadWrite;
352 public override bool CanSeek {
358 public virtual bool IsAsync {
370 public override long Length {
372 if (safeHandle.IsClosed)
373 throw new ObjectDisposedException ("Stream has been closed");
376 throw new NotSupportedException ("The stream does not support seeking");
378 // Buffered data might change the length of the stream
379 FlushBufferIfDirty ();
383 long length = MonoIO.GetLength (safeHandle, out error);
385 if (error != MonoIOError.ERROR_SUCCESS) {
386 // don't leak the path information for isolated storage
387 throw MonoIO.GetException (GetSecureFileName (name), error);
394 public override long Position {
396 if (safeHandle.IsClosed)
397 throw new ObjectDisposedException ("Stream has been closed");
399 if (CanSeek == false)
400 throw new NotSupportedException("The stream does not support seeking");
403 return(buf_start + buf_offset);
405 // If the handle was leaked outside we always ask the real handle
408 long ret = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
410 if (error != MonoIOError.ERROR_SUCCESS) {
411 // don't leak the path information for isolated storage
412 throw MonoIO.GetException (GetSecureFileName (name), error);
418 if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
420 Seek (value, SeekOrigin.Begin);
424 [Obsolete ("Use SafeFileHandle instead")]
425 public virtual IntPtr Handle {
426 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
427 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
429 var handle = safeHandle.DangerousGetHandle ();
436 public virtual SafeFileHandle SafeFileHandle {
437 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
438 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
450 InitBuffer (0, true);
455 public override int ReadByte ()
457 if (safeHandle.IsClosed)
458 throw new ObjectDisposedException ("Stream has been closed");
461 throw new NotSupportedException ("Stream does not support reading");
464 int n = ReadData (safeHandle, buf, 0, 1);
465 if (n == 0) return -1;
468 else if (buf_offset >= buf_length) {
475 return buf [buf_offset ++];
478 public override void WriteByte (byte value)
480 if (safeHandle.IsClosed)
481 throw new ObjectDisposedException ("Stream has been closed");
484 throw new NotSupportedException ("Stream does not support writing");
486 if (buf_offset == buf_size)
489 if (buf_size == 0) { // No buffering
497 buf [buf_offset ++] = value;
498 if (buf_offset > buf_length)
499 buf_length = buf_offset;
504 public override int Read ([In,Out] byte[] array, int offset, int count)
506 if (safeHandle.IsClosed)
507 throw new ObjectDisposedException ("Stream has been closed");
509 throw new ArgumentNullException ("array");
511 throw new NotSupportedException ("Stream does not support reading");
512 int len = array.Length;
514 throw new ArgumentOutOfRangeException ("offset", "< 0");
516 throw new ArgumentOutOfRangeException ("count", "< 0");
518 throw new ArgumentException ("destination offset is beyond array size");
519 // reordered to avoid possible integer overflow
520 if (offset > len - count)
521 throw new ArgumentException ("Reading would overrun buffer");
524 IAsyncResult ares = BeginRead (array, offset, count, null, null);
525 return EndRead (ares);
528 return ReadInternal (array, offset, count);
531 int ReadInternal (byte [] dest, int offset, int count)
533 int n = ReadSegment (dest, offset, count);
541 if (count > buf_size) {
542 /* Read as much as we can, up
546 n = ReadData (safeHandle, dest, offset+n, count);
548 /* Make the next buffer read
549 * start from the right place
554 n = ReadSegment (dest, offset+copied, count);
560 delegate int ReadDelegate (byte [] buffer, int offset, int count);
562 public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes,
563 AsyncCallback userCallback, object stateObject)
565 if (safeHandle.IsClosed)
566 throw new ObjectDisposedException ("Stream has been closed");
569 throw new NotSupportedException ("This stream does not support reading");
572 throw new ArgumentNullException ("array");
575 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
578 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
580 // reordered to avoid possible integer overflow
581 if (numBytes > array.Length - offset)
582 throw new ArgumentException ("Buffer too small. numBytes/offset wrong.");
585 return base.BeginRead (array, offset, numBytes, userCallback, stateObject);
587 ReadDelegate r = new ReadDelegate (ReadInternal);
588 return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
591 public override int EndRead (IAsyncResult asyncResult)
593 if (asyncResult == null)
594 throw new ArgumentNullException ("asyncResult");
597 return base.EndRead (asyncResult);
599 AsyncResult ares = asyncResult as AsyncResult;
601 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
603 ReadDelegate r = ares.AsyncDelegate as ReadDelegate;
605 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
607 return r.EndInvoke (asyncResult);
610 public override void Write (byte[] array, int offset, int count)
612 if (safeHandle.IsClosed)
613 throw new ObjectDisposedException ("Stream has been closed");
615 throw new ArgumentNullException ("array");
617 throw new ArgumentOutOfRangeException ("offset", "< 0");
619 throw new ArgumentOutOfRangeException ("count", "< 0");
620 // ordered to avoid possible integer overflow
621 if (offset > array.Length - count)
622 throw new ArgumentException ("Reading would overrun buffer");
624 throw new NotSupportedException ("Stream does not support writing");
627 IAsyncResult ares = BeginWrite (array, offset, count, null, null);
632 WriteInternal (array, offset, count);
635 void WriteInternal (byte [] src, int offset, int count)
637 if (count > buf_size) {
638 // shortcut for long writes
643 if (CanSeek && !isExposed) {
644 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
645 if (error != MonoIOError.ERROR_SUCCESS)
646 throw MonoIO.GetException (GetSecureFileName (name), error);
652 int n = MonoIO.Write (safeHandle, src, offset, wcount, out error);
653 if (error != MonoIOError.ERROR_SUCCESS)
654 throw MonoIO.GetException (GetSecureFileName (name), error);
665 int n = WriteSegment (src, offset + copied, count);
678 delegate void WriteDelegate (byte [] buffer, int offset, int count);
680 public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
681 AsyncCallback userCallback, object stateObject)
683 if (safeHandle.IsClosed)
684 throw new ObjectDisposedException ("Stream has been closed");
687 throw new NotSupportedException ("This stream does not support writing");
690 throw new ArgumentNullException ("array");
693 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
696 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
698 // reordered to avoid possible integer overflow
699 if (numBytes > array.Length - offset)
700 throw new ArgumentException ("array too small. numBytes/offset wrong.");
703 return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
705 FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
706 result.BytesRead = -1;
707 result.Count = numBytes;
708 result.OriginalCount = numBytes;
711 MemoryStream ms = new MemoryStream ();
713 ms.Write (array, offset, numBytes);
715 // Set arguments to new compounded buffer
717 array = ms.ToArray ();
718 numBytes = array.Length;
721 WriteDelegate w = WriteInternal;
722 return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
725 public override void EndWrite (IAsyncResult asyncResult)
727 if (asyncResult == null)
728 throw new ArgumentNullException ("asyncResult");
731 base.EndWrite (asyncResult);
735 AsyncResult ares = asyncResult as AsyncResult;
737 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
739 WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
741 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
743 w.EndInvoke (asyncResult);
747 public override long Seek (long offset, SeekOrigin origin)
751 if (safeHandle.IsClosed)
752 throw new ObjectDisposedException ("Stream has been closed");
756 if(CanSeek == false) {
757 throw new NotSupportedException("The stream does not support seeking");
762 pos = Length + offset;
765 case SeekOrigin.Current:
766 pos = Position + offset;
769 case SeekOrigin.Begin:
774 throw new ArgumentException ("origin", "Invalid SeekOrigin");
778 /* LAMESPEC: shouldn't this be
779 * ArgumentOutOfRangeException?
781 throw new IOException("Attempted to Seek before the beginning of the stream");
784 if(pos < this.append_startpos) {
785 /* More undocumented crap */
786 throw new IOException("Can't seek back over pre-existing data in append mode");
793 buf_start = MonoIO.Seek (safeHandle, pos, SeekOrigin.Begin, out error);
795 if (error != MonoIOError.ERROR_SUCCESS) {
796 // don't leak the path information for isolated storage
797 throw MonoIO.GetException (GetSecureFileName (name), error);
803 public override void SetLength (long value)
805 if (safeHandle.IsClosed)
806 throw new ObjectDisposedException ("Stream has been closed");
809 throw new NotSupportedException("The stream does not support seeking");
811 if(CanWrite == false)
812 throw new NotSupportedException("The stream does not support writing");
815 throw new ArgumentOutOfRangeException("value is less than 0");
821 MonoIO.SetLength (safeHandle, value, out error);
822 if (error != MonoIOError.ERROR_SUCCESS) {
823 // don't leak the path information for isolated storage
824 throw MonoIO.GetException (GetSecureFileName (name), error);
827 if (Position > value)
831 public override void Flush ()
833 if (safeHandle.IsClosed)
834 throw new ObjectDisposedException ("Stream has been closed");
839 public virtual void Flush (bool flushToDisk)
841 if (safeHandle.IsClosed)
842 throw new ObjectDisposedException ("Stream has been closed");
846 // This does the fsync
849 MonoIO.Flush (safeHandle, out error);
853 public virtual void Lock (long position, long length)
855 if (safeHandle.IsClosed)
856 throw new ObjectDisposedException ("Stream has been closed");
858 throw new ArgumentOutOfRangeException ("position must not be negative");
861 throw new ArgumentOutOfRangeException ("length must not be negative");
866 MonoIO.Lock (safeHandle, position, length, out error);
867 if (error != MonoIOError.ERROR_SUCCESS) {
868 // don't leak the path information for isolated storage
869 throw MonoIO.GetException (GetSecureFileName (name), error);
873 public virtual void Unlock (long position, long length)
875 if (safeHandle.IsClosed)
876 throw new ObjectDisposedException ("Stream has been closed");
878 throw new ArgumentOutOfRangeException ("position must not be negative");
881 throw new ArgumentOutOfRangeException ("length must not be negative");
886 MonoIO.Unlock (safeHandle, position, length, out error);
887 if (error != MonoIOError.ERROR_SUCCESS) {
888 // don't leak the path information for isolated storage
889 throw MonoIO.GetException (GetSecureFileName (name), error);
900 protected override void Dispose (bool disposing)
902 Exception exc = null;
903 if (safeHandle != null && !safeHandle.IsClosed) {
905 // If the FileStream is in "exposed" status
906 // it means that we do not have a buffer(we write the data without buffering)
907 // therefor we don't and can't flush the buffer becouse we don't have one.
909 } catch (Exception e) {
916 MonoIO.Close (safeHandle.DangerousGetHandle (), out error);
917 if (error != MonoIOError.ERROR_SUCCESS) {
918 // don't leak the path information for isolated storage
919 throw MonoIO.GetException (GetSecureFileName (name), error);
922 safeHandle.DangerousRelease ();
929 if (disposing && buf != null) {
930 if (buf.Length == DefaultBufferSize && buf_recycle == null) {
931 lock (buf_recycle_lock) {
932 if (buf_recycle == null) {
939 GC.SuppressFinalize (this);
946 public FileSecurity GetAccessControl ()
948 if (safeHandle.IsClosed)
949 throw new ObjectDisposedException ("Stream has been closed");
951 return new FileSecurity (SafeFileHandle,
952 AccessControlSections.Owner |
953 AccessControlSections.Group |
954 AccessControlSections.Access);
957 public void SetAccessControl (FileSecurity fileSecurity)
959 if (safeHandle.IsClosed)
960 throw new ObjectDisposedException ("Stream has been closed");
962 if (null == fileSecurity)
963 throw new ArgumentNullException ("fileSecurity");
965 fileSecurity.PersistModifications (SafeFileHandle);
969 public override Task FlushAsync (CancellationToken cancellationToken)
971 if (safeHandle.IsClosed)
972 throw new ObjectDisposedException ("Stream has been closed");
974 return base.FlushAsync (cancellationToken);
977 public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
979 return base.ReadAsync (buffer, offset, count, cancellationToken);
982 public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
984 return base.WriteAsync (buffer, offset, count, cancellationToken);
989 // ReadSegment, WriteSegment, FlushBuffer,
990 // RefillBuffer and ReadData should only be called
991 // when the Monitor lock is held, but these methods
992 // grab it again just to be safe.
994 private int ReadSegment (byte [] dest, int dest_offset, int count)
996 count = Math.Min (count, buf_length - buf_offset);
999 // Use the fastest method, all range checks has been done
1000 Buffer.InternalBlockCopy (buf, buf_offset, dest, dest_offset, count);
1001 buf_offset += count;
1007 private int WriteSegment (byte [] src, int src_offset,
1010 if (count > buf_size - buf_offset) {
1011 count = buf_size - buf_offset;
1015 Buffer.BlockCopy (src, src_offset,
1018 buf_offset += count;
1019 if (buf_offset > buf_length) {
1020 buf_length = buf_offset;
1032 // if (st == null) {
1035 if (CanSeek == true && !isExposed) {
1036 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
1038 if (error != MonoIOError.ERROR_SUCCESS) {
1039 // don't leak the path information for isolated storage
1040 throw MonoIO.GetException (GetSecureFileName (name), error);
1044 int wcount = buf_length;
1047 int n = MonoIO.Write (safeHandle, buf, offset, buf_length, out error);
1048 if (error != MonoIOError.ERROR_SUCCESS) {
1049 // don't leak the path information for isolated storage
1050 throw MonoIO.GetException (GetSecureFileName (name), error);
1056 // st.Write (buf, 0, buf_length);
1060 buf_start += buf_offset;
1061 buf_offset = buf_length = 0;
1065 private void FlushBufferIfDirty ()
1071 private void RefillBuffer ()
1075 buf_length = ReadData (safeHandle, buf, 0, buf_size);
1078 private int ReadData (SafeHandle safeHandle, byte[] buf, int offset,
1084 /* when async == true, if we get here we don't suport AIO or it's disabled
1085 * and we're using the threadpool */
1086 amount = MonoIO.Read (safeHandle, buf, offset, count, out error);
1087 if (error == MonoIOError.ERROR_BROKEN_PIPE) {
1088 amount = 0; // might not be needed, but well...
1089 } else if (error != MonoIOError.ERROR_SUCCESS) {
1090 // don't leak the path information for isolated storage
1091 throw MonoIO.GetException (GetSecureFileName (name), error);
1094 /* Check for read error */
1096 throw new IOException ();
1102 void InitBuffer (int size, bool isZeroSize)
1109 throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
1111 size = Math.Max (size, 8);
1114 // Instead of allocating a new default buffer use the
1115 // last one if there is any available
1117 if (size <= DefaultBufferSize && buf_recycle != null) {
1118 lock (buf_recycle_lock) {
1119 if (buf_recycle != null) {
1127 buf = new byte [size];
1129 Array.Clear (buf, 0, size);
1134 // buf_offset = buf_length = 0;
1135 // buf_dirty = false;
1138 private string GetSecureFileName (string filename)
1140 return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
1143 private string GetSecureFileName (string filename, bool full)
1145 return (anonymous) ? Path.GetFileName (filename) :
1146 (full) ? Path.GetFullPath (filename) : filename;
1151 internal const int DefaultBufferSize = 4096;
1153 // Input buffer ready for recycling
1154 static byte[] buf_recycle;
1155 static readonly object buf_recycle_lock = new object ();
1157 private byte [] buf; // the buffer
1158 private string name = "[Unknown]"; // name of file.
1160 private SafeFileHandle safeHandle;
1161 private bool isExposed;
1163 private long append_startpos;
1165 private FileAccess access;
1168 private bool canseek;
1169 private bool anonymous;
1170 private bool buf_dirty; // true if buffer has been written to
1172 private int buf_size; // capacity in bytes
1173 private int buf_length; // number of valid bytes in buffer
1174 private int buf_offset; // position of next byte
1175 private long buf_start; // location of buffer in file