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 if (Directory.Exists (path)) {
192 // don't leak the path information for isolated storage
193 string msg = Locale.GetText ("Access to the path '{0}' is denied.");
194 throw new UnauthorizedAccessException (String.Format (msg, GetSecureFileName (path, false)));
197 /* Append streams can't be read (see FileMode
200 if (mode==FileMode.Append &&
201 (access&FileAccess.Read)==FileAccess.Read) {
202 throw new ArgumentException("Append access can be requested only in write-only mode.");
205 if ((access & FileAccess.Write) == 0 &&
206 (mode != FileMode.Open && mode != FileMode.OpenOrCreate)) {
207 string msg = Locale.GetText ("Combining FileMode: {0} with " +
208 "FileAccess: {1} is invalid.");
209 throw new ArgumentException (string.Format (msg, access, mode));
212 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
215 if (Path.DirectorySeparatorChar != '/' && path.IndexOf ('/') >= 0)
216 dname = Path.GetDirectoryName (Path.GetFullPath (path));
218 dname = Path.GetDirectoryName (path);
219 if (dname.Length > 0) {
220 string fp = Path.GetFullPath (dname);
221 if (!Directory.Exists (fp)) {
222 // don't leak the path information for isolated storage
223 string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
224 string fname = (anonymous) ? dname : Path.GetFullPath (path);
225 throw new DirectoryNotFoundException (String.Format (msg, fname));
229 if (access == FileAccess.Read && mode != FileMode.Create && mode != FileMode.OpenOrCreate &&
230 mode != FileMode.CreateNew && !File.Exists (path)) {
231 // don't leak the path information for isolated storage
232 string msg = Locale.GetText ("Could not find file \"{0}\".");
233 string fname = GetSecureFileName (path);
234 throw new FileNotFoundException (String.Format (msg, fname), fname);
237 // IsolatedStorage needs to keep the Name property to the default "[Unknown]"
241 // TODO: demand permissions
245 var nativeHandle = MonoIO.Open (path, mode, access, share, options, out error);
247 if (nativeHandle == MonoIO.InvalidHandle) {
248 // don't leak the path information for isolated storage
249 throw MonoIO.GetException (GetSecureFileName (path), error);
252 this.safeHandle = new SafeFileHandle (nativeHandle, false);
254 this.access = access;
257 /* Can we open non-files by name? */
259 if (MonoIO.GetFileType (safeHandle, out error) == MonoFileType.Disk) {
261 this.async = (options & FileOptions.Asynchronous) != 0;
263 this.canseek = false;
268 if (access == FileAccess.Read && canseek && (bufferSize == DefaultBufferSize)) {
269 /* Avoid allocating a large buffer for small files */
271 if (bufferSize > len) {
272 bufferSize = (int)(len < 1000 ? 1000 : len);
276 InitBuffer (bufferSize, false);
278 if (mode==FileMode.Append) {
279 this.Seek (0, SeekOrigin.End);
280 this.append_startpos=this.Position;
282 this.append_startpos=0;
286 private void Init (SafeFileHandle safeHandle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isConsoleWrapper)
288 if (!isConsoleWrapper && safeHandle.IsInvalid)
289 throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
290 if (access < FileAccess.Read || access > FileAccess.ReadWrite)
291 throw new ArgumentOutOfRangeException ("access");
292 if (!isConsoleWrapper && bufferSize <= 0)
293 throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
296 MonoFileType ftype = MonoIO.GetFileType (safeHandle, out error);
298 if (error != MonoIOError.ERROR_SUCCESS) {
299 throw MonoIO.GetException (name, error);
302 if (ftype == MonoFileType.Unknown) {
303 throw new IOException ("Invalid handle.");
304 } else if (ftype == MonoFileType.Disk) {
307 this.canseek = false;
310 this.safeHandle = safeHandle;
312 this.access = access;
313 this.owner = ownsHandle;
314 this.async = isAsync;
315 this.anonymous = false;
318 buf_start = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
319 if (error != MonoIOError.ERROR_SUCCESS) {
320 throw MonoIO.GetException (name, error);
324 /* Can't set append mode */
325 this.append_startpos=0;
330 public override bool CanRead {
332 return access == FileAccess.Read ||
333 access == FileAccess.ReadWrite;
337 public override bool CanWrite {
339 return access == FileAccess.Write ||
340 access == FileAccess.ReadWrite;
344 public override bool CanSeek {
350 public virtual bool IsAsync {
362 public override long Length {
364 if (safeHandle.IsClosed)
365 throw new ObjectDisposedException ("Stream has been closed");
368 throw new NotSupportedException ("The stream does not support seeking");
370 // Buffered data might change the length of the stream
371 FlushBufferIfDirty ();
375 long length = MonoIO.GetLength (safeHandle, out error);
377 if (error != MonoIOError.ERROR_SUCCESS) {
378 // don't leak the path information for isolated storage
379 throw MonoIO.GetException (GetSecureFileName (name), error);
386 public override long Position {
388 if (safeHandle.IsClosed)
389 throw new ObjectDisposedException ("Stream has been closed");
391 if (CanSeek == false)
392 throw new NotSupportedException("The stream does not support seeking");
395 return(buf_start + buf_offset);
397 // If the handle was leaked outside we always ask the real handle
400 long ret = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
402 if (error != MonoIOError.ERROR_SUCCESS) {
403 // don't leak the path information for isolated storage
404 throw MonoIO.GetException (GetSecureFileName (name), error);
410 if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
412 Seek (value, SeekOrigin.Begin);
416 [Obsolete ("Use SafeFileHandle instead")]
417 public virtual IntPtr Handle {
418 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
419 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
421 var handle = safeHandle.DangerousGetHandle ();
428 public virtual SafeFileHandle SafeFileHandle {
429 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
430 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
442 InitBuffer (0, true);
447 public override int ReadByte ()
449 if (safeHandle.IsClosed)
450 throw new ObjectDisposedException ("Stream has been closed");
453 throw new NotSupportedException ("Stream does not support reading");
456 int n = ReadData (safeHandle, buf, 0, 1);
457 if (n == 0) return -1;
460 else if (buf_offset >= buf_length) {
467 return buf [buf_offset ++];
470 public override void WriteByte (byte value)
472 if (safeHandle.IsClosed)
473 throw new ObjectDisposedException ("Stream has been closed");
476 throw new NotSupportedException ("Stream does not support writing");
478 if (buf_offset == buf_size)
481 if (buf_size == 0) { // No buffering
489 buf [buf_offset ++] = value;
490 if (buf_offset > buf_length)
491 buf_length = buf_offset;
496 public override int Read ([In,Out] byte[] array, int offset, int count)
498 if (safeHandle.IsClosed)
499 throw new ObjectDisposedException ("Stream has been closed");
501 throw new ArgumentNullException ("array");
503 throw new NotSupportedException ("Stream does not support reading");
504 int len = array.Length;
506 throw new ArgumentOutOfRangeException ("offset", "< 0");
508 throw new ArgumentOutOfRangeException ("count", "< 0");
510 throw new ArgumentException ("destination offset is beyond array size");
511 // reordered to avoid possible integer overflow
512 if (offset > len - count)
513 throw new ArgumentException ("Reading would overrun buffer");
516 IAsyncResult ares = BeginRead (array, offset, count, null, null);
517 return EndRead (ares);
520 return ReadInternal (array, offset, count);
523 int ReadInternal (byte [] dest, int offset, int count)
525 int n = ReadSegment (dest, offset, count);
533 if (count > buf_size) {
534 /* Read as much as we can, up
538 n = ReadData (safeHandle, dest, offset+n, count);
540 /* Make the next buffer read
541 * start from the right place
546 n = ReadSegment (dest, offset+copied, count);
552 delegate int ReadDelegate (byte [] buffer, int offset, int count);
554 public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes,
555 AsyncCallback userCallback, object stateObject)
557 if (safeHandle.IsClosed)
558 throw new ObjectDisposedException ("Stream has been closed");
561 throw new NotSupportedException ("This stream does not support reading");
564 throw new ArgumentNullException ("array");
567 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
570 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
572 // reordered to avoid possible integer overflow
573 if (numBytes > array.Length - offset)
574 throw new ArgumentException ("Buffer too small. numBytes/offset wrong.");
577 return base.BeginRead (array, offset, numBytes, userCallback, stateObject);
579 ReadDelegate r = new ReadDelegate (ReadInternal);
580 return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
583 public override int EndRead (IAsyncResult asyncResult)
585 if (asyncResult == null)
586 throw new ArgumentNullException ("asyncResult");
589 return base.EndRead (asyncResult);
591 AsyncResult ares = asyncResult as AsyncResult;
593 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
595 ReadDelegate r = ares.AsyncDelegate as ReadDelegate;
597 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
599 return r.EndInvoke (asyncResult);
602 public override void Write (byte[] array, int offset, int count)
604 if (safeHandle.IsClosed)
605 throw new ObjectDisposedException ("Stream has been closed");
607 throw new ArgumentNullException ("array");
609 throw new ArgumentOutOfRangeException ("offset", "< 0");
611 throw new ArgumentOutOfRangeException ("count", "< 0");
612 // ordered to avoid possible integer overflow
613 if (offset > array.Length - count)
614 throw new ArgumentException ("Reading would overrun buffer");
616 throw new NotSupportedException ("Stream does not support writing");
619 IAsyncResult ares = BeginWrite (array, offset, count, null, null);
624 WriteInternal (array, offset, count);
627 void WriteInternal (byte [] src, int offset, int count)
629 if (count > buf_size) {
630 // shortcut for long writes
635 if (CanSeek && !isExposed) {
636 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
637 if (error != MonoIOError.ERROR_SUCCESS)
638 throw MonoIO.GetException (GetSecureFileName (name), error);
644 int n = MonoIO.Write (safeHandle, src, offset, wcount, out error);
645 if (error != MonoIOError.ERROR_SUCCESS)
646 throw MonoIO.GetException (GetSecureFileName (name), error);
657 int n = WriteSegment (src, offset + copied, count);
670 delegate void WriteDelegate (byte [] buffer, int offset, int count);
672 public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
673 AsyncCallback userCallback, object stateObject)
675 if (safeHandle.IsClosed)
676 throw new ObjectDisposedException ("Stream has been closed");
679 throw new NotSupportedException ("This stream does not support writing");
682 throw new ArgumentNullException ("array");
685 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
688 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
690 // reordered to avoid possible integer overflow
691 if (numBytes > array.Length - offset)
692 throw new ArgumentException ("array too small. numBytes/offset wrong.");
695 return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
697 FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
698 result.BytesRead = -1;
699 result.Count = numBytes;
700 result.OriginalCount = numBytes;
703 MemoryStream ms = new MemoryStream ();
705 ms.Write (array, offset, numBytes);
707 // Set arguments to new compounded buffer
709 array = ms.ToArray ();
710 numBytes = array.Length;
713 WriteDelegate w = WriteInternal;
714 return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
717 public override void EndWrite (IAsyncResult asyncResult)
719 if (asyncResult == null)
720 throw new ArgumentNullException ("asyncResult");
723 base.EndWrite (asyncResult);
727 AsyncResult ares = asyncResult as AsyncResult;
729 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
731 WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
733 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
735 w.EndInvoke (asyncResult);
739 public override long Seek (long offset, SeekOrigin origin)
743 if (safeHandle.IsClosed)
744 throw new ObjectDisposedException ("Stream has been closed");
748 if(CanSeek == false) {
749 throw new NotSupportedException("The stream does not support seeking");
754 pos = Length + offset;
757 case SeekOrigin.Current:
758 pos = Position + offset;
761 case SeekOrigin.Begin:
766 throw new ArgumentException ("origin", "Invalid SeekOrigin");
770 /* LAMESPEC: shouldn't this be
771 * ArgumentOutOfRangeException?
773 throw new IOException("Attempted to Seek before the beginning of the stream");
776 if(pos < this.append_startpos) {
777 /* More undocumented crap */
778 throw new IOException("Can't seek back over pre-existing data in append mode");
785 buf_start = MonoIO.Seek (safeHandle, pos, SeekOrigin.Begin, out error);
787 if (error != MonoIOError.ERROR_SUCCESS) {
788 // don't leak the path information for isolated storage
789 throw MonoIO.GetException (GetSecureFileName (name), error);
795 public override void SetLength (long value)
797 if (safeHandle.IsClosed)
798 throw new ObjectDisposedException ("Stream has been closed");
801 throw new NotSupportedException("The stream does not support seeking");
803 if(CanWrite == false)
804 throw new NotSupportedException("The stream does not support writing");
807 throw new ArgumentOutOfRangeException("value is less than 0");
813 MonoIO.SetLength (safeHandle, value, out error);
814 if (error != MonoIOError.ERROR_SUCCESS) {
815 // don't leak the path information for isolated storage
816 throw MonoIO.GetException (GetSecureFileName (name), error);
819 if (Position > value)
823 public override void Flush ()
825 if (safeHandle.IsClosed)
826 throw new ObjectDisposedException ("Stream has been closed");
831 public virtual void Flush (bool flushToDisk)
833 if (safeHandle.IsClosed)
834 throw new ObjectDisposedException ("Stream has been closed");
838 // This does the fsync
841 MonoIO.Flush (safeHandle, out error);
845 public virtual void Lock (long position, long length)
847 if (safeHandle.IsClosed)
848 throw new ObjectDisposedException ("Stream has been closed");
850 throw new ArgumentOutOfRangeException ("position must not be negative");
853 throw new ArgumentOutOfRangeException ("length must not be negative");
858 MonoIO.Lock (safeHandle, position, length, out error);
859 if (error != MonoIOError.ERROR_SUCCESS) {
860 // don't leak the path information for isolated storage
861 throw MonoIO.GetException (GetSecureFileName (name), error);
865 public virtual void Unlock (long position, long length)
867 if (safeHandle.IsClosed)
868 throw new ObjectDisposedException ("Stream has been closed");
870 throw new ArgumentOutOfRangeException ("position must not be negative");
873 throw new ArgumentOutOfRangeException ("length must not be negative");
878 MonoIO.Unlock (safeHandle, position, length, out error);
879 if (error != MonoIOError.ERROR_SUCCESS) {
880 // don't leak the path information for isolated storage
881 throw MonoIO.GetException (GetSecureFileName (name), error);
892 protected override void Dispose (bool disposing)
894 Exception exc = null;
895 if (safeHandle != null && !safeHandle.IsClosed) {
897 // If the FileStream is in "exposed" status
898 // it means that we do not have a buffer(we write the data without buffering)
899 // therefor we don't and can't flush the buffer becouse we don't have one.
901 } catch (Exception e) {
908 MonoIO.Close (safeHandle.DangerousGetHandle (), out error);
909 if (error != MonoIOError.ERROR_SUCCESS) {
910 // don't leak the path information for isolated storage
911 throw MonoIO.GetException (GetSecureFileName (name), error);
914 safeHandle.DangerousRelease ();
921 if (disposing && buf != null) {
922 if (buf.Length == DefaultBufferSize && buf_recycle == null) {
923 lock (buf_recycle_lock) {
924 if (buf_recycle == null) {
931 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);
959 public override Task FlushAsync (CancellationToken cancellationToken)
961 if (safeHandle.IsClosed)
962 throw new ObjectDisposedException ("Stream has been closed");
964 return base.FlushAsync (cancellationToken);
967 public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
969 return base.ReadAsync (buffer, offset, count, cancellationToken);
972 public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
974 return base.WriteAsync (buffer, offset, count, cancellationToken);
979 // ReadSegment, WriteSegment, FlushBuffer,
980 // RefillBuffer and ReadData should only be called
981 // when the Monitor lock is held, but these methods
982 // grab it again just to be safe.
984 private int ReadSegment (byte [] dest, int dest_offset, int count)
986 count = Math.Min (count, buf_length - buf_offset);
989 // Use the fastest method, all range checks has been done
990 Buffer.InternalBlockCopy (buf, buf_offset, dest, dest_offset, count);
997 private int WriteSegment (byte [] src, int src_offset,
1000 if (count > buf_size - buf_offset) {
1001 count = buf_size - buf_offset;
1005 Buffer.BlockCopy (src, src_offset,
1008 buf_offset += count;
1009 if (buf_offset > buf_length) {
1010 buf_length = buf_offset;
1022 // if (st == null) {
1025 if (CanSeek == true && !isExposed) {
1026 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
1028 if (error != MonoIOError.ERROR_SUCCESS) {
1029 // don't leak the path information for isolated storage
1030 throw MonoIO.GetException (GetSecureFileName (name), error);
1034 int wcount = buf_length;
1037 int n = MonoIO.Write (safeHandle, buf, offset, buf_length, 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);
1046 // st.Write (buf, 0, buf_length);
1050 buf_start += buf_offset;
1051 buf_offset = buf_length = 0;
1055 private void FlushBufferIfDirty ()
1061 private void RefillBuffer ()
1065 buf_length = ReadData (safeHandle, buf, 0, buf_size);
1068 private int ReadData (SafeHandle safeHandle, byte[] buf, int offset,
1074 /* when async == true, if we get here we don't suport AIO or it's disabled
1075 * and we're using the threadpool */
1076 amount = MonoIO.Read (safeHandle, buf, offset, count, out error);
1077 if (error == MonoIOError.ERROR_BROKEN_PIPE) {
1078 amount = 0; // might not be needed, but well...
1079 } else if (error != MonoIOError.ERROR_SUCCESS) {
1080 // don't leak the path information for isolated storage
1081 throw MonoIO.GetException (GetSecureFileName (name), error);
1084 /* Check for read error */
1086 throw new IOException ();
1092 void InitBuffer (int size, bool isZeroSize)
1099 throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
1101 size = Math.Max (size, 8);
1104 // Instead of allocating a new default buffer use the
1105 // last one if there is any available
1107 if (size <= DefaultBufferSize && buf_recycle != null) {
1108 lock (buf_recycle_lock) {
1109 if (buf_recycle != null) {
1117 buf = new byte [size];
1119 Array.Clear (buf, 0, size);
1124 // buf_offset = buf_length = 0;
1125 // buf_dirty = false;
1128 private string GetSecureFileName (string filename)
1130 return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
1133 private string GetSecureFileName (string filename, bool full)
1135 return (anonymous) ? Path.GetFileName (filename) :
1136 (full) ? Path.GetFullPath (filename) : filename;
1141 internal const int DefaultBufferSize = 4096;
1143 // Input buffer ready for recycling
1144 static byte[] buf_recycle;
1145 static readonly object buf_recycle_lock = new object ();
1147 private byte [] buf; // the buffer
1148 private string name = "[Unknown]"; // name of file.
1150 private SafeFileHandle safeHandle;
1151 private bool isExposed;
1153 private long append_startpos;
1155 private FileAccess access;
1158 private bool canseek;
1159 private bool anonymous;
1160 private bool buf_dirty; // true if buffer has been written to
1162 private int buf_size; // capacity in bytes
1163 private int buf_length; // number of valid bytes in buffer
1164 private int buf_offset; // position of next byte
1165 private long buf_start; // location of buffer in file