FileStream.cs 30 KB

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