FileStream.cs 32 KB

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