FileStream.cs 32 KB

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