FileStream.cs 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. //
  2. // System.IO.FileStream.cs
  3. //
  4. // Authors:
  5. // Dietmar Maurer ([email protected])
  6. // Dan Lewis ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected])
  8. // Marek Safar ([email protected])
  9. //
  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).
  13. //
  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:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  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.
  32. //
  33. using System.Collections;
  34. using System.Globalization;
  35. using System.Runtime.CompilerServices;
  36. using System.Runtime.InteropServices;
  37. using System.Runtime.Remoting.Messaging;
  38. using System.Security;
  39. using System.Security.Permissions;
  40. using System.Threading;
  41. using Microsoft.Win32.SafeHandles;
  42. #if NET_2_1
  43. using System.IO.IsolatedStorage;
  44. #else
  45. using System.Security.AccessControl;
  46. #endif
  47. using System.Threading.Tasks;
  48. namespace System.IO
  49. {
  50. [ComVisible (true)]
  51. public class FileStream : Stream
  52. {
  53. // construct from handle
  54. [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
  55. public FileStream (IntPtr handle, FileAccess access)
  56. : 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) {}
  60. [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")]
  61. public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
  62. : this (handle, access, ownsHandle, bufferSize, false, false) {}
  63. [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")]
  64. public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
  65. : this (handle, access, ownsHandle, bufferSize, isAsync, false) {}
  66. [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
  67. internal FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isZeroSize)
  68. {
  69. if (handle == MonoIO.InvalidHandle)
  70. throw new ArgumentException ("handle", Locale.GetText ("Invalid."));
  71. Init (new SafeFileHandle (handle, false), access, ownsHandle, bufferSize, isAsync, isZeroSize);
  72. }
  73. // construct from filename
  74. public FileStream (string path, FileMode mode)
  75. : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.Read, DefaultBufferSize, false, FileOptions.None)
  76. {
  77. }
  78. public FileStream (string path, FileMode mode, FileAccess access)
  79. : this (path, mode, access, access == FileAccess.Write ? FileShare.None : FileShare.Read, DefaultBufferSize, false, false)
  80. {
  81. }
  82. public FileStream (string path, FileMode mode, FileAccess access, FileShare share)
  83. : this (path, mode, access, share, DefaultBufferSize, false, FileOptions.None)
  84. {
  85. }
  86. public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
  87. : this (path, mode, access, share, bufferSize, false, FileOptions.None)
  88. {
  89. }
  90. public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
  91. : this (path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
  92. {
  93. }
  94. public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
  95. : this (path, mode, access, share, bufferSize, false, options)
  96. {
  97. }
  98. #if !NET_2_1
  99. public FileStream (SafeFileHandle handle, FileAccess access)
  100. :this(handle, access, DefaultBufferSize, false)
  101. {
  102. }
  103. public FileStream (SafeFileHandle handle, FileAccess access,
  104. int bufferSize)
  105. :this(handle, access, bufferSize, false)
  106. {
  107. }
  108. public FileStream (SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
  109. {
  110. Init (handle, access, false, bufferSize, isAsync, false);
  111. }
  112. [MonoLimitation ("This ignores the rights parameter")]
  113. public FileStream (string path, FileMode mode,
  114. FileSystemRights rights, FileShare share,
  115. int bufferSize, FileOptions options)
  116. : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
  117. {
  118. }
  119. [MonoLimitation ("This ignores the rights and fileSecurity parameters")]
  120. public FileStream (string path, FileMode mode,
  121. FileSystemRights rights, FileShare share,
  122. int bufferSize, FileOptions options,
  123. FileSecurity fileSecurity)
  124. : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
  125. {
  126. }
  127. #endif
  128. internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath = false, bool checkHost = false)
  129. : this (path, mode, access, share, bufferSize, false, options)
  130. {
  131. }
  132. internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool isAsync, bool anonymous)
  133. : this (path, mode, access, share, bufferSize, anonymous, isAsync ? FileOptions.Asynchronous : FileOptions.None)
  134. {
  135. }
  136. internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool anonymous, FileOptions options)
  137. {
  138. if (path == null) {
  139. throw new ArgumentNullException ("path");
  140. }
  141. if (path.Length == 0) {
  142. throw new ArgumentException ("Path is empty");
  143. }
  144. this.anonymous = anonymous;
  145. // ignore the Inheritable flag
  146. share &= ~FileShare.Inheritable;
  147. if (bufferSize <= 0)
  148. throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
  149. if (mode < FileMode.CreateNew || mode > FileMode.Append) {
  150. #if NET_2_1
  151. if (anonymous)
  152. throw new ArgumentException ("mode", "Enum value was out of legal range.");
  153. else
  154. #endif
  155. throw new ArgumentOutOfRangeException ("mode", "Enum value was out of legal range.");
  156. }
  157. if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
  158. throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
  159. }
  160. if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
  161. throw new ArgumentOutOfRangeException ("share", "Enum value was out of legal range.");
  162. }
  163. if (path.IndexOfAny (Path.InvalidPathChars) != -1) {
  164. throw new ArgumentException ("Name has invalid chars");
  165. }
  166. if (Directory.Exists (path)) {
  167. // don't leak the path information for isolated storage
  168. string msg = Locale.GetText ("Access to the path '{0}' is denied.");
  169. throw new UnauthorizedAccessException (String.Format (msg, GetSecureFileName (path, false)));
  170. }
  171. /* Append streams can't be read (see FileMode
  172. * docs)
  173. */
  174. if (mode==FileMode.Append &&
  175. (access&FileAccess.Read)==FileAccess.Read) {
  176. throw new ArgumentException("Append access can be requested only in write-only mode.");
  177. }
  178. if ((access & FileAccess.Write) == 0 &&
  179. (mode != FileMode.Open && mode != FileMode.OpenOrCreate)) {
  180. string msg = Locale.GetText ("Combining FileMode: {0} with " +
  181. "FileAccess: {1} is invalid.");
  182. throw new ArgumentException (string.Format (msg, access, mode));
  183. }
  184. SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
  185. string dname;
  186. if (Path.DirectorySeparatorChar != '/' && path.IndexOf ('/') >= 0)
  187. dname = Path.GetDirectoryName (Path.GetFullPath (path));
  188. else
  189. dname = Path.GetDirectoryName (path);
  190. if (dname.Length > 0) {
  191. string fp = Path.GetFullPath (dname);
  192. if (!Directory.Exists (fp)) {
  193. // don't leak the path information for isolated storage
  194. string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
  195. string fname = (anonymous) ? dname : Path.GetFullPath (path);
  196. throw new DirectoryNotFoundException (String.Format (msg, fname));
  197. }
  198. }
  199. if (access == FileAccess.Read && mode != FileMode.Create && mode != FileMode.OpenOrCreate &&
  200. mode != FileMode.CreateNew && !File.Exists (path)) {
  201. // don't leak the path information for isolated storage
  202. string msg = Locale.GetText ("Could not find file \"{0}\".");
  203. string fname = GetSecureFileName (path);
  204. throw new FileNotFoundException (String.Format (msg, fname), fname);
  205. }
  206. // IsolatedStorage needs to keep the Name property to the default "[Unknown]"
  207. if (!anonymous)
  208. this.name = path;
  209. // TODO: demand permissions
  210. MonoIOError error;
  211. var nativeHandle = MonoIO.Open (path, mode, access, share, options, out error);
  212. if (nativeHandle == MonoIO.InvalidHandle) {
  213. // don't leak the path information for isolated storage
  214. throw MonoIO.GetException (GetSecureFileName (path), error);
  215. }
  216. this.safeHandle = new SafeFileHandle (nativeHandle, false);
  217. this.access = access;
  218. this.owner = true;
  219. /* Can we open non-files by name? */
  220. if (MonoIO.GetFileType (safeHandle, out error) == MonoFileType.Disk) {
  221. this.canseek = true;
  222. this.async = (options & FileOptions.Asynchronous) != 0;
  223. } else {
  224. this.canseek = false;
  225. this.async = false;
  226. }
  227. if (access == FileAccess.Read && canseek && (bufferSize == DefaultBufferSize)) {
  228. /* Avoid allocating a large buffer for small files */
  229. long len = Length;
  230. if (bufferSize > len) {
  231. bufferSize = (int)(len < 1000 ? 1000 : len);
  232. }
  233. }
  234. InitBuffer (bufferSize, false);
  235. if (mode==FileMode.Append) {
  236. this.Seek (0, SeekOrigin.End);
  237. this.append_startpos=this.Position;
  238. } else {
  239. this.append_startpos=0;
  240. }
  241. }
  242. private void Init (SafeFileHandle safeHandle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isZeroSize)
  243. {
  244. if (access < FileAccess.Read || access > FileAccess.ReadWrite)
  245. throw new ArgumentOutOfRangeException ("access");
  246. MonoIOError error;
  247. MonoFileType ftype = MonoIO.GetFileType (safeHandle, out error);
  248. if (error != MonoIOError.ERROR_SUCCESS) {
  249. throw MonoIO.GetException (name, error);
  250. }
  251. if (ftype == MonoFileType.Unknown) {
  252. throw new IOException ("Invalid handle.");
  253. } else if (ftype == MonoFileType.Disk) {
  254. this.canseek = true;
  255. } else {
  256. this.canseek = false;
  257. }
  258. this.safeHandle = safeHandle;
  259. ExposeHandle ();
  260. this.access = access;
  261. this.owner = ownsHandle;
  262. this.async = isAsync;
  263. this.anonymous = false;
  264. if (canseek) {
  265. buf_start = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
  266. if (error != MonoIOError.ERROR_SUCCESS) {
  267. throw MonoIO.GetException (name, error);
  268. }
  269. }
  270. /* Can't set append mode */
  271. this.append_startpos=0;
  272. }
  273. // properties
  274. public override bool CanRead {
  275. get {
  276. return access == FileAccess.Read ||
  277. access == FileAccess.ReadWrite;
  278. }
  279. }
  280. public override bool CanWrite {
  281. get {
  282. return access == FileAccess.Write ||
  283. access == FileAccess.ReadWrite;
  284. }
  285. }
  286. public override bool CanSeek {
  287. get {
  288. return(canseek);
  289. }
  290. }
  291. public virtual bool IsAsync {
  292. get {
  293. return (async);
  294. }
  295. }
  296. public string Name {
  297. get {
  298. return name;
  299. }
  300. }
  301. public override long Length {
  302. get {
  303. if (safeHandle.IsClosed)
  304. throw new ObjectDisposedException ("Stream has been closed");
  305. if (!CanSeek)
  306. throw new NotSupportedException ("The stream does not support seeking");
  307. // Buffered data might change the length of the stream
  308. FlushBufferIfDirty ();
  309. MonoIOError error;
  310. long length = MonoIO.GetLength (safeHandle, out error);
  311. if (error != MonoIOError.ERROR_SUCCESS) {
  312. // don't leak the path information for isolated storage
  313. throw MonoIO.GetException (GetSecureFileName (name), error);
  314. }
  315. return(length);
  316. }
  317. }
  318. public override long Position {
  319. get {
  320. if (safeHandle.IsClosed)
  321. throw new ObjectDisposedException ("Stream has been closed");
  322. if (CanSeek == false)
  323. throw new NotSupportedException("The stream does not support seeking");
  324. if (!isExposed)
  325. return(buf_start + buf_offset);
  326. // If the handle was leaked outside we always ask the real handle
  327. MonoIOError error;
  328. long ret = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
  329. if (error != MonoIOError.ERROR_SUCCESS) {
  330. // don't leak the path information for isolated storage
  331. throw MonoIO.GetException (GetSecureFileName (name), error);
  332. }
  333. return ret;
  334. }
  335. set {
  336. if(value < 0) {
  337. throw new ArgumentOutOfRangeException("Attempt to set the position to a negative value");
  338. }
  339. Seek (value, SeekOrigin.Begin);
  340. }
  341. }
  342. [Obsolete ("Use SafeFileHandle instead")]
  343. public virtual IntPtr Handle {
  344. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  345. [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
  346. get {
  347. var handle = safeHandle.DangerousGetHandle ();
  348. if (!isExposed)
  349. ExposeHandle ();
  350. return handle;
  351. }
  352. }
  353. public virtual SafeFileHandle SafeFileHandle {
  354. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  355. [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
  356. get {
  357. if (!isExposed)
  358. ExposeHandle ();
  359. return safeHandle;
  360. }
  361. }
  362. void ExposeHandle ()
  363. {
  364. isExposed = true;
  365. FlushBuffer ();
  366. InitBuffer (0, true);
  367. }
  368. // methods
  369. public override int ReadByte ()
  370. {
  371. if (safeHandle.IsClosed)
  372. throw new ObjectDisposedException ("Stream has been closed");
  373. if (!CanRead)
  374. throw new NotSupportedException ("Stream does not support reading");
  375. if (buf_size == 0) {
  376. int n = ReadData (safeHandle, buf, 0, 1);
  377. if (n == 0) return -1;
  378. else return buf[0];
  379. }
  380. else if (buf_offset >= buf_length) {
  381. RefillBuffer ();
  382. if (buf_length == 0)
  383. return -1;
  384. }
  385. return buf [buf_offset ++];
  386. }
  387. public override void WriteByte (byte value)
  388. {
  389. if (safeHandle.IsClosed)
  390. throw new ObjectDisposedException ("Stream has been closed");
  391. if (!CanWrite)
  392. throw new NotSupportedException ("Stream does not support writing");
  393. if (buf_offset == buf_size)
  394. FlushBuffer ();
  395. if (buf_size == 0) { // No buffering
  396. buf [0] = value;
  397. buf_dirty = true;
  398. buf_length = 1;
  399. FlushBuffer ();
  400. return;
  401. }
  402. buf [buf_offset ++] = value;
  403. if (buf_offset > buf_length)
  404. buf_length = buf_offset;
  405. buf_dirty = true;
  406. }
  407. public override int Read ([In,Out] byte[] array, int offset, int count)
  408. {
  409. if (safeHandle.IsClosed)
  410. throw new ObjectDisposedException ("Stream has been closed");
  411. if (array == null)
  412. throw new ArgumentNullException ("array");
  413. if (!CanRead)
  414. throw new NotSupportedException ("Stream does not support reading");
  415. int len = array.Length;
  416. if (offset < 0)
  417. throw new ArgumentOutOfRangeException ("offset", "< 0");
  418. if (count < 0)
  419. throw new ArgumentOutOfRangeException ("count", "< 0");
  420. if (offset > len)
  421. throw new ArgumentException ("destination offset is beyond array size");
  422. // reordered to avoid possible integer overflow
  423. if (offset > len - count)
  424. throw new ArgumentException ("Reading would overrun buffer");
  425. if (async) {
  426. IAsyncResult ares = BeginRead (array, offset, count, null, null);
  427. return EndRead (ares);
  428. }
  429. return ReadInternal (array, offset, count);
  430. }
  431. int ReadInternal (byte [] dest, int offset, int count)
  432. {
  433. int n = ReadSegment (dest, offset, count);
  434. if (n == count) {
  435. return count;
  436. }
  437. int copied = n;
  438. count -= n;
  439. if (count > buf_size) {
  440. /* Read as much as we can, up
  441. * to count bytes
  442. */
  443. FlushBuffer();
  444. n = ReadData (safeHandle, dest, offset+n, count);
  445. /* Make the next buffer read
  446. * start from the right place
  447. */
  448. buf_start += n;
  449. } else {
  450. RefillBuffer ();
  451. n = ReadSegment (dest, offset+copied, count);
  452. }
  453. return copied + n;
  454. }
  455. delegate int ReadDelegate (byte [] buffer, int offset, int count);
  456. public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes,
  457. AsyncCallback userCallback, object stateObject)
  458. {
  459. if (safeHandle.IsClosed)
  460. throw new ObjectDisposedException ("Stream has been closed");
  461. if (!CanRead)
  462. throw new NotSupportedException ("This stream does not support reading");
  463. if (array == null)
  464. throw new ArgumentNullException ("array");
  465. if (numBytes < 0)
  466. throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
  467. if (offset < 0)
  468. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  469. // reordered to avoid possible integer overflow
  470. if (numBytes > array.Length - offset)
  471. throw new ArgumentException ("Buffer too small. numBytes/offset wrong.");
  472. if (!async)
  473. return base.BeginRead (array, offset, numBytes, userCallback, stateObject);
  474. ReadDelegate r = new ReadDelegate (ReadInternal);
  475. return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
  476. }
  477. public override int EndRead (IAsyncResult asyncResult)
  478. {
  479. if (asyncResult == null)
  480. throw new ArgumentNullException ("asyncResult");
  481. if (!async)
  482. return base.EndRead (asyncResult);
  483. AsyncResult ares = asyncResult as AsyncResult;
  484. if (ares == null)
  485. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  486. ReadDelegate r = ares.AsyncDelegate as ReadDelegate;
  487. if (r == null)
  488. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  489. return r.EndInvoke (asyncResult);
  490. }
  491. public override void Write (byte[] array, int offset, int count)
  492. {
  493. if (safeHandle.IsClosed)
  494. throw new ObjectDisposedException ("Stream has been closed");
  495. if (array == null)
  496. throw new ArgumentNullException ("array");
  497. if (offset < 0)
  498. throw new ArgumentOutOfRangeException ("offset", "< 0");
  499. if (count < 0)
  500. throw new ArgumentOutOfRangeException ("count", "< 0");
  501. // ordered to avoid possible integer overflow
  502. if (offset > array.Length - count)
  503. throw new ArgumentException ("Reading would overrun buffer");
  504. if (!CanWrite)
  505. throw new NotSupportedException ("Stream does not support writing");
  506. if (async) {
  507. IAsyncResult ares = BeginWrite (array, offset, count, null, null);
  508. EndWrite (ares);
  509. return;
  510. }
  511. WriteInternal (array, offset, count);
  512. }
  513. void WriteInternal (byte [] src, int offset, int count)
  514. {
  515. if (count > buf_size) {
  516. // shortcut for long writes
  517. MonoIOError error;
  518. FlushBuffer ();
  519. int wcount = count;
  520. while (wcount > 0){
  521. int n = MonoIO.Write (safeHandle, src, offset, wcount, out error);
  522. if (error != MonoIOError.ERROR_SUCCESS)
  523. throw MonoIO.GetException (GetSecureFileName (name), error);
  524. wcount -= n;
  525. offset += n;
  526. }
  527. buf_start += count;
  528. } else {
  529. int copied = 0;
  530. while (count > 0) {
  531. int n = WriteSegment (src, offset + copied, count);
  532. copied += n;
  533. count -= n;
  534. if (count == 0) {
  535. break;
  536. }
  537. FlushBuffer ();
  538. }
  539. }
  540. }
  541. delegate void WriteDelegate (byte [] buffer, int offset, int count);
  542. public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
  543. AsyncCallback userCallback, object stateObject)
  544. {
  545. if (safeHandle.IsClosed)
  546. throw new ObjectDisposedException ("Stream has been closed");
  547. if (!CanWrite)
  548. throw new NotSupportedException ("This stream does not support writing");
  549. if (array == null)
  550. throw new ArgumentNullException ("array");
  551. if (numBytes < 0)
  552. throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
  553. if (offset < 0)
  554. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  555. // reordered to avoid possible integer overflow
  556. if (numBytes > array.Length - offset)
  557. throw new ArgumentException ("array too small. numBytes/offset wrong.");
  558. if (!async)
  559. return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
  560. FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
  561. result.BytesRead = -1;
  562. result.Count = numBytes;
  563. result.OriginalCount = numBytes;
  564. /*
  565. if (buf_dirty) {
  566. MemoryStream ms = new MemoryStream ();
  567. FlushBuffer (ms);
  568. ms.Write (array, offset, numBytes);
  569. // Set arguments to new compounded buffer
  570. offset = 0;
  571. array = ms.ToArray ();
  572. numBytes = array.Length;
  573. }
  574. */
  575. WriteDelegate w = WriteInternal;
  576. return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
  577. }
  578. public override void EndWrite (IAsyncResult asyncResult)
  579. {
  580. if (asyncResult == null)
  581. throw new ArgumentNullException ("asyncResult");
  582. if (!async) {
  583. base.EndWrite (asyncResult);
  584. return;
  585. }
  586. AsyncResult ares = asyncResult as AsyncResult;
  587. if (ares == null)
  588. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  589. WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
  590. if (w == null)
  591. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  592. w.EndInvoke (asyncResult);
  593. return;
  594. }
  595. public override long Seek (long offset, SeekOrigin origin)
  596. {
  597. long pos;
  598. if (safeHandle.IsClosed)
  599. throw new ObjectDisposedException ("Stream has been closed");
  600. // make absolute
  601. if(CanSeek == false) {
  602. throw new NotSupportedException("The stream does not support seeking");
  603. }
  604. switch (origin) {
  605. case SeekOrigin.End:
  606. pos = Length + offset;
  607. break;
  608. case SeekOrigin.Current:
  609. pos = Position + offset;
  610. break;
  611. case SeekOrigin.Begin:
  612. pos = offset;
  613. break;
  614. default:
  615. throw new ArgumentException ("origin", "Invalid SeekOrigin");
  616. }
  617. if (pos < 0) {
  618. /* LAMESPEC: shouldn't this be
  619. * ArgumentOutOfRangeException?
  620. */
  621. throw new IOException("Attempted to Seek before the beginning of the stream");
  622. }
  623. if(pos < this.append_startpos) {
  624. /* More undocumented crap */
  625. throw new IOException("Can't seek back over pre-existing data in append mode");
  626. }
  627. FlushBuffer ();
  628. MonoIOError error;
  629. buf_start = MonoIO.Seek (safeHandle, pos, SeekOrigin.Begin, out error);
  630. if (error != MonoIOError.ERROR_SUCCESS) {
  631. // don't leak the path information for isolated storage
  632. throw MonoIO.GetException (GetSecureFileName (name), error);
  633. }
  634. return(buf_start);
  635. }
  636. public override void SetLength (long value)
  637. {
  638. if (safeHandle.IsClosed)
  639. throw new ObjectDisposedException ("Stream has been closed");
  640. if(CanSeek == false)
  641. throw new NotSupportedException("The stream does not support seeking");
  642. if(CanWrite == false)
  643. throw new NotSupportedException("The stream does not support writing");
  644. if(value < 0)
  645. throw new ArgumentOutOfRangeException("value is less than 0");
  646. FlushBuffer ();
  647. MonoIOError error;
  648. MonoIO.SetLength (safeHandle, value, out error);
  649. if (error != MonoIOError.ERROR_SUCCESS) {
  650. // don't leak the path information for isolated storage
  651. throw MonoIO.GetException (GetSecureFileName (name), error);
  652. }
  653. if (Position > value)
  654. Position = value;
  655. }
  656. public override void Flush ()
  657. {
  658. if (safeHandle.IsClosed)
  659. throw new ObjectDisposedException ("Stream has been closed");
  660. FlushBuffer ();
  661. }
  662. public virtual void Flush (bool flushToDisk)
  663. {
  664. if (safeHandle.IsClosed)
  665. throw new ObjectDisposedException ("Stream has been closed");
  666. FlushBuffer ();
  667. // This does the fsync
  668. if (flushToDisk){
  669. MonoIOError error;
  670. MonoIO.Flush (safeHandle, out error);
  671. }
  672. }
  673. public virtual void Lock (long position, long length)
  674. {
  675. if (safeHandle.IsClosed)
  676. throw new ObjectDisposedException ("Stream has been closed");
  677. if (position < 0) {
  678. throw new ArgumentOutOfRangeException ("position must not be negative");
  679. }
  680. if (length < 0) {
  681. throw new ArgumentOutOfRangeException ("length must not be negative");
  682. }
  683. MonoIOError error;
  684. MonoIO.Lock (safeHandle, position, length, out error);
  685. if (error != MonoIOError.ERROR_SUCCESS) {
  686. // don't leak the path information for isolated storage
  687. throw MonoIO.GetException (GetSecureFileName (name), error);
  688. }
  689. }
  690. public virtual void Unlock (long position, long length)
  691. {
  692. if (safeHandle.IsClosed)
  693. throw new ObjectDisposedException ("Stream has been closed");
  694. if (position < 0) {
  695. throw new ArgumentOutOfRangeException ("position must not be negative");
  696. }
  697. if (length < 0) {
  698. throw new ArgumentOutOfRangeException ("length must not be negative");
  699. }
  700. MonoIOError error;
  701. MonoIO.Unlock (safeHandle, position, length, out error);
  702. if (error != MonoIOError.ERROR_SUCCESS) {
  703. // don't leak the path information for isolated storage
  704. throw MonoIO.GetException (GetSecureFileName (name), error);
  705. }
  706. }
  707. // protected
  708. ~FileStream ()
  709. {
  710. Dispose (false);
  711. }
  712. protected override void Dispose (bool disposing)
  713. {
  714. Exception exc = null;
  715. if (safeHandle != null && !safeHandle.IsClosed) {
  716. try {
  717. // If the FileStream is in "exposed" status
  718. // it means that we do not have a buffer(we write the data without buffering)
  719. // therefor we don't and can't flush the buffer becouse we don't have one.
  720. FlushBuffer ();
  721. } catch (Exception e) {
  722. exc = e;
  723. }
  724. if (owner) {
  725. MonoIOError error;
  726. MonoIO.Close (safeHandle.DangerousGetHandle (), out error);
  727. if (error != MonoIOError.ERROR_SUCCESS) {
  728. // don't leak the path information for isolated storage
  729. throw MonoIO.GetException (GetSecureFileName (name), error);
  730. }
  731. safeHandle.DangerousRelease ();
  732. }
  733. }
  734. canseek = false;
  735. access = 0;
  736. if (disposing && buf != null) {
  737. if (buf.Length == DefaultBufferSize && buf_recycle == null) {
  738. lock (buf_recycle_lock) {
  739. if (buf_recycle == null) {
  740. buf_recycle = buf;
  741. }
  742. }
  743. }
  744. buf = null;
  745. GC.SuppressFinalize (this);
  746. }
  747. if (exc != null)
  748. throw exc;
  749. }
  750. #if !NET_2_1
  751. public FileSecurity GetAccessControl ()
  752. {
  753. if (safeHandle.IsClosed)
  754. throw new ObjectDisposedException ("Stream has been closed");
  755. return new FileSecurity (SafeFileHandle,
  756. AccessControlSections.Owner |
  757. AccessControlSections.Group |
  758. AccessControlSections.Access);
  759. }
  760. public void SetAccessControl (FileSecurity fileSecurity)
  761. {
  762. if (safeHandle.IsClosed)
  763. throw new ObjectDisposedException ("Stream has been closed");
  764. if (null == fileSecurity)
  765. throw new ArgumentNullException ("fileSecurity");
  766. fileSecurity.PersistModifications (SafeFileHandle);
  767. }
  768. #endif
  769. public override Task FlushAsync (CancellationToken cancellationToken)
  770. {
  771. if (safeHandle.IsClosed)
  772. throw new ObjectDisposedException ("Stream has been closed");
  773. return base.FlushAsync (cancellationToken);
  774. }
  775. public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  776. {
  777. return base.ReadAsync (buffer, offset, count, cancellationToken);
  778. }
  779. public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  780. {
  781. return base.WriteAsync (buffer, offset, count, cancellationToken);
  782. }
  783. // private.
  784. // ReadSegment, WriteSegment, FlushBuffer,
  785. // RefillBuffer and ReadData should only be called
  786. // when the Monitor lock is held, but these methods
  787. // grab it again just to be safe.
  788. private int ReadSegment (byte [] dest, int dest_offset, int count)
  789. {
  790. count = Math.Min (count, buf_length - buf_offset);
  791. if (count > 0) {
  792. // Use the fastest method, all range checks has been done
  793. Buffer.BlockCopyInternal (buf, buf_offset, dest, dest_offset, count);
  794. buf_offset += count;
  795. }
  796. return count;
  797. }
  798. private int WriteSegment (byte [] src, int src_offset,
  799. int count)
  800. {
  801. if (count > buf_size - buf_offset) {
  802. count = buf_size - buf_offset;
  803. }
  804. if (count > 0) {
  805. Buffer.BlockCopy (src, src_offset,
  806. buf, buf_offset,
  807. count);
  808. buf_offset += count;
  809. if (buf_offset > buf_length) {
  810. buf_length = buf_offset;
  811. }
  812. buf_dirty = true;
  813. }
  814. return(count);
  815. }
  816. void FlushBuffer ()
  817. {
  818. if (buf_dirty) {
  819. // if (st == null) {
  820. MonoIOError error;
  821. if (CanSeek == true && !isExposed) {
  822. MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
  823. if (error != MonoIOError.ERROR_SUCCESS) {
  824. // don't leak the path information for isolated storage
  825. throw MonoIO.GetException (GetSecureFileName (name), error);
  826. }
  827. }
  828. int wcount = buf_length;
  829. int offset = 0;
  830. while (wcount > 0){
  831. int n = MonoIO.Write (safeHandle, buf, 0, buf_length, out error);
  832. if (error != MonoIOError.ERROR_SUCCESS) {
  833. // don't leak the path information for isolated storage
  834. throw MonoIO.GetException (GetSecureFileName (name), error);
  835. }
  836. wcount -= n;
  837. offset += n;
  838. }
  839. // } else {
  840. // st.Write (buf, 0, buf_length);
  841. // }
  842. }
  843. buf_start += buf_offset;
  844. buf_offset = buf_length = 0;
  845. buf_dirty = false;
  846. }
  847. private void FlushBufferIfDirty ()
  848. {
  849. if (buf_dirty)
  850. FlushBuffer ();
  851. }
  852. private void RefillBuffer ()
  853. {
  854. FlushBuffer ();
  855. buf_length = ReadData (safeHandle, buf, 0, buf_size);
  856. }
  857. private int ReadData (SafeHandle safeHandle, byte[] buf, int offset,
  858. int count)
  859. {
  860. MonoIOError error;
  861. int amount = 0;
  862. /* when async == true, if we get here we don't suport AIO or it's disabled
  863. * and we're using the threadpool */
  864. amount = MonoIO.Read (safeHandle, buf, offset, count, out error);
  865. if (error == MonoIOError.ERROR_BROKEN_PIPE) {
  866. amount = 0; // might not be needed, but well...
  867. } else if (error != MonoIOError.ERROR_SUCCESS) {
  868. // don't leak the path information for isolated storage
  869. throw MonoIO.GetException (GetSecureFileName (name), error);
  870. }
  871. /* Check for read error */
  872. if(amount == -1) {
  873. throw new IOException ();
  874. }
  875. return(amount);
  876. }
  877. void InitBuffer (int size, bool isZeroSize)
  878. {
  879. if (isZeroSize) {
  880. size = 0;
  881. buf = new byte[1];
  882. } else {
  883. if (size <= 0)
  884. throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
  885. size = Math.Max (size, 8);
  886. //
  887. // Instead of allocating a new default buffer use the
  888. // last one if there is any available
  889. //
  890. if (size <= DefaultBufferSize && buf_recycle != null) {
  891. lock (buf_recycle_lock) {
  892. if (buf_recycle != null) {
  893. buf = buf_recycle;
  894. buf_recycle = null;
  895. }
  896. }
  897. }
  898. if (buf == null)
  899. buf = new byte [size];
  900. else
  901. Array.Clear (buf, 0, size);
  902. }
  903. buf_size = size;
  904. // buf_start = 0;
  905. // buf_offset = buf_length = 0;
  906. // buf_dirty = false;
  907. }
  908. private string GetSecureFileName (string filename)
  909. {
  910. return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
  911. }
  912. private string GetSecureFileName (string filename, bool full)
  913. {
  914. return (anonymous) ? Path.GetFileName (filename) :
  915. (full) ? Path.GetFullPath (filename) : filename;
  916. }
  917. // fields
  918. internal const int DefaultBufferSize = 4096;
  919. // Input buffer ready for recycling
  920. static byte[] buf_recycle;
  921. static readonly object buf_recycle_lock = new object ();
  922. private byte [] buf; // the buffer
  923. private string name = "[Unknown]"; // name of file.
  924. private SafeFileHandle safeHandle;
  925. private bool isExposed;
  926. private long append_startpos;
  927. private FileAccess access;
  928. private bool owner;
  929. private bool async;
  930. private bool canseek;
  931. private bool anonymous;
  932. private bool buf_dirty; // true if buffer has been written to
  933. private int buf_size; // capacity in bytes
  934. private int buf_length; // number of valid bytes in buffer
  935. private int buf_offset; // position of next byte
  936. private long buf_start; // location of buffer in file
  937. }
  938. }