FileStream.cs 30 KB

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