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. int wcount = count;
  532. while (wcount > 0){
  533. int n = MonoIO.Write (handle, src, offset, wcount, out error);
  534. if (error != MonoIOError.ERROR_SUCCESS)
  535. throw MonoIO.GetException (GetSecureFileName (name), error);
  536. wcount -= n;
  537. offset += n;
  538. }
  539. buf_start += count;
  540. } else {
  541. int copied = 0;
  542. while (count > 0) {
  543. int n = WriteSegment (src, offset + copied, count);
  544. copied += n;
  545. count -= n;
  546. if (count == 0) {
  547. break;
  548. }
  549. FlushBuffer ();
  550. }
  551. }
  552. }
  553. delegate void WriteDelegate (byte [] buffer, int offset, int count);
  554. public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
  555. AsyncCallback userCallback, object stateObject)
  556. {
  557. if (handle == MonoIO.InvalidHandle)
  558. throw new ObjectDisposedException ("Stream has been closed");
  559. if (!CanWrite)
  560. throw new NotSupportedException ("This stream does not support writing");
  561. if (array == null)
  562. throw new ArgumentNullException ("array");
  563. if (numBytes < 0)
  564. throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
  565. if (offset < 0)
  566. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  567. // reordered to avoid possible integer overflow
  568. if (numBytes > array.Length - offset)
  569. throw new ArgumentException ("array too small. numBytes/offset wrong.");
  570. if (!async)
  571. return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
  572. FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
  573. result.BytesRead = -1;
  574. result.Count = numBytes;
  575. result.OriginalCount = numBytes;
  576. if (buf_dirty) {
  577. MemoryStream ms = new MemoryStream ();
  578. FlushBuffer (ms);
  579. ms.Write (array, offset, numBytes);
  580. offset = 0;
  581. numBytes = (int) ms.Length;
  582. }
  583. WriteDelegate w = new WriteDelegate (WriteInternal);
  584. return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
  585. }
  586. public override void EndWrite (IAsyncResult asyncResult)
  587. {
  588. if (asyncResult == null)
  589. throw new ArgumentNullException ("asyncResult");
  590. if (!async) {
  591. base.EndWrite (asyncResult);
  592. return;
  593. }
  594. AsyncResult ares = asyncResult as AsyncResult;
  595. if (ares == null)
  596. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  597. WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
  598. if (w == null)
  599. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  600. w.EndInvoke (asyncResult);
  601. return;
  602. }
  603. public override long Seek (long offset, SeekOrigin origin)
  604. {
  605. long pos;
  606. if (handle == MonoIO.InvalidHandle)
  607. throw new ObjectDisposedException ("Stream has been closed");
  608. // make absolute
  609. if(CanSeek == false) {
  610. throw new NotSupportedException("The stream does not support seeking");
  611. }
  612. switch (origin) {
  613. case SeekOrigin.End:
  614. pos = Length + offset;
  615. break;
  616. case SeekOrigin.Current:
  617. pos = Position + offset;
  618. break;
  619. case SeekOrigin.Begin:
  620. pos = offset;
  621. break;
  622. default:
  623. throw new ArgumentException ("origin", "Invalid SeekOrigin");
  624. }
  625. if (pos < 0) {
  626. /* LAMESPEC: shouldn't this be
  627. * ArgumentOutOfRangeException?
  628. */
  629. throw new IOException("Attempted to Seek before the beginning of the stream");
  630. }
  631. if(pos < this.append_startpos) {
  632. /* More undocumented crap */
  633. throw new IOException("Can't seek back over pre-existing data in append mode");
  634. }
  635. FlushBuffer ();
  636. MonoIOError error;
  637. buf_start = MonoIO.Seek (handle, pos,
  638. SeekOrigin.Begin,
  639. out error);
  640. if (error != MonoIOError.ERROR_SUCCESS) {
  641. // don't leak the path information for isolated storage
  642. throw MonoIO.GetException (GetSecureFileName (name), error);
  643. }
  644. return(buf_start);
  645. }
  646. public override void SetLength (long value)
  647. {
  648. if (handle == MonoIO.InvalidHandle)
  649. throw new ObjectDisposedException ("Stream has been closed");
  650. if(CanSeek == false)
  651. throw new NotSupportedException("The stream does not support seeking");
  652. if(CanWrite == false)
  653. throw new NotSupportedException("The stream does not support writing");
  654. if(value < 0)
  655. throw new ArgumentOutOfRangeException("value is less than 0");
  656. Flush ();
  657. MonoIOError error;
  658. MonoIO.SetLength (handle, value, out error);
  659. if (error != MonoIOError.ERROR_SUCCESS) {
  660. // don't leak the path information for isolated storage
  661. throw MonoIO.GetException (GetSecureFileName (name), error);
  662. }
  663. if (Position > value)
  664. Position = value;
  665. }
  666. public override void Flush ()
  667. {
  668. if (handle == MonoIO.InvalidHandle)
  669. throw new ObjectDisposedException ("Stream has been closed");
  670. FlushBuffer ();
  671. }
  672. #if NET_4_0
  673. public virtual void Flush (bool flushToDisk)
  674. {
  675. FlushBuffer ();
  676. // This does the fsync
  677. if (flushToDisk)
  678. MonoIO.Flush (handle);
  679. }
  680. #endif
  681. public virtual void Lock (long position, long length)
  682. {
  683. if (handle == MonoIO.InvalidHandle)
  684. throw new ObjectDisposedException ("Stream has been closed");
  685. if (position < 0) {
  686. throw new ArgumentOutOfRangeException ("position must not be negative");
  687. }
  688. if (length < 0) {
  689. throw new ArgumentOutOfRangeException ("length must not be negative");
  690. }
  691. if (handle == MonoIO.InvalidHandle) {
  692. throw new ObjectDisposedException ("Stream has been closed");
  693. }
  694. MonoIOError error;
  695. MonoIO.Lock (handle, position, length, out error);
  696. if (error != MonoIOError.ERROR_SUCCESS) {
  697. // don't leak the path information for isolated storage
  698. throw MonoIO.GetException (GetSecureFileName (name), error);
  699. }
  700. }
  701. public virtual void Unlock (long position, long length)
  702. {
  703. if (handle == MonoIO.InvalidHandle)
  704. throw new ObjectDisposedException ("Stream has been closed");
  705. if (position < 0) {
  706. throw new ArgumentOutOfRangeException ("position must not be negative");
  707. }
  708. if (length < 0) {
  709. throw new ArgumentOutOfRangeException ("length must not be negative");
  710. }
  711. MonoIOError error;
  712. MonoIO.Unlock (handle, position, length, out error);
  713. if (error != MonoIOError.ERROR_SUCCESS) {
  714. // don't leak the path information for isolated storage
  715. throw MonoIO.GetException (GetSecureFileName (name), error);
  716. }
  717. }
  718. // protected
  719. ~FileStream ()
  720. {
  721. Dispose (false);
  722. }
  723. protected override void Dispose (bool disposing)
  724. {
  725. if (handle != MonoIO.InvalidHandle) {
  726. FlushBuffer ();
  727. if (owner) {
  728. MonoIOError error;
  729. MonoIO.Close (handle, out error);
  730. if (error != MonoIOError.ERROR_SUCCESS) {
  731. // don't leak the path information for isolated storage
  732. throw MonoIO.GetException (GetSecureFileName (name), error);
  733. }
  734. handle = MonoIO.InvalidHandle;
  735. }
  736. }
  737. canseek = false;
  738. access = 0;
  739. if (disposing) {
  740. buf = null;
  741. }
  742. if (disposing)
  743. GC.SuppressFinalize (this);
  744. }
  745. #if !NET_2_1
  746. public FileSecurity GetAccessControl ()
  747. {
  748. throw new NotImplementedException ();
  749. }
  750. public void SetAccessControl (FileSecurity fileSecurity)
  751. {
  752. throw new NotImplementedException ();
  753. }
  754. #endif
  755. // private.
  756. // ReadSegment, WriteSegment, FlushBuffer,
  757. // RefillBuffer and ReadData should only be called
  758. // when the Monitor lock is held, but these methods
  759. // grab it again just to be safe.
  760. private int ReadSegment (byte [] dest, int dest_offset, int count)
  761. {
  762. if (count > buf_length - buf_offset) {
  763. count = buf_length - buf_offset;
  764. }
  765. if (count > 0) {
  766. Buffer.BlockCopy (buf, buf_offset,
  767. dest, dest_offset,
  768. count);
  769. buf_offset += count;
  770. }
  771. return(count);
  772. }
  773. private int WriteSegment (byte [] src, int src_offset,
  774. int count)
  775. {
  776. if (count > buf_size - buf_offset) {
  777. count = buf_size - buf_offset;
  778. }
  779. if (count > 0) {
  780. Buffer.BlockCopy (src, src_offset,
  781. buf, buf_offset,
  782. count);
  783. buf_offset += count;
  784. if (buf_offset > buf_length) {
  785. buf_length = buf_offset;
  786. }
  787. buf_dirty = true;
  788. }
  789. return(count);
  790. }
  791. void FlushBuffer (Stream st)
  792. {
  793. if (buf_dirty) {
  794. MonoIOError error;
  795. if (CanSeek == true) {
  796. MonoIO.Seek (handle, buf_start,
  797. SeekOrigin.Begin,
  798. out error);
  799. if (error != MonoIOError.ERROR_SUCCESS) {
  800. // don't leak the path information for isolated storage
  801. throw MonoIO.GetException (GetSecureFileName (name), error);
  802. }
  803. }
  804. if (st == null) {
  805. int wcount = buf_length;
  806. int offset = 0;
  807. while (wcount > 0){
  808. int n = MonoIO.Write (handle, buf, 0, buf_length, out error);
  809. if (error != MonoIOError.ERROR_SUCCESS) {
  810. // don't leak the path information for isolated storage
  811. throw MonoIO.GetException (GetSecureFileName (name), error);
  812. }
  813. wcount -= n;
  814. offset += n;
  815. }
  816. } else {
  817. st.Write (buf, 0, buf_length);
  818. }
  819. }
  820. buf_start += buf_offset;
  821. buf_offset = buf_length = 0;
  822. buf_dirty = false;
  823. }
  824. private void FlushBuffer ()
  825. {
  826. FlushBuffer (null);
  827. }
  828. private void FlushBufferIfDirty ()
  829. {
  830. if (buf_dirty)
  831. FlushBuffer (null);
  832. }
  833. private void RefillBuffer ()
  834. {
  835. FlushBuffer (null);
  836. buf_length = ReadData (handle, buf, 0,
  837. buf_size);
  838. }
  839. private int ReadData (IntPtr handle, byte[] buf, int offset,
  840. int count)
  841. {
  842. MonoIOError error;
  843. int amount = 0;
  844. /* when async == true, if we get here we don't suport AIO or it's disabled
  845. * and we're using the threadpool */
  846. amount = MonoIO.Read (handle, buf, offset, count, out error);
  847. if (error == MonoIOError.ERROR_BROKEN_PIPE) {
  848. amount = 0; // might not be needed, but well...
  849. } else if (error != MonoIOError.ERROR_SUCCESS) {
  850. // don't leak the path information for isolated storage
  851. throw MonoIO.GetException (GetSecureFileName (name), error);
  852. }
  853. /* Check for read error */
  854. if(amount == -1) {
  855. throw new IOException ();
  856. }
  857. return(amount);
  858. }
  859. private void InitBuffer (int size, bool noBuffering)
  860. {
  861. if (noBuffering) {
  862. size = 0;
  863. // We need a buffer for the ReadByte method. This buffer won't
  864. // be used for anything else since buf_size==0.
  865. buf = new byte [1];
  866. }
  867. else {
  868. if (size <= 0)
  869. throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
  870. if (size < 8)
  871. size = 8;
  872. buf = new byte [size];
  873. }
  874. buf_size = size;
  875. buf_start = 0;
  876. buf_offset = buf_length = 0;
  877. buf_dirty = false;
  878. }
  879. private string GetSecureFileName (string filename)
  880. {
  881. return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
  882. }
  883. private string GetSecureFileName (string filename, bool full)
  884. {
  885. return (anonymous) ? Path.GetFileName (filename) :
  886. (full) ? Path.GetFullPath (filename) : filename;
  887. }
  888. // fields
  889. internal const int DefaultBufferSize = 8192;
  890. private FileAccess access;
  891. private bool owner;
  892. private bool async;
  893. private bool canseek;
  894. private long append_startpos;
  895. private bool anonymous;
  896. private byte [] buf; // the buffer
  897. private int buf_size; // capacity in bytes
  898. private int buf_length; // number of valid bytes in buffer
  899. private int buf_offset; // position of next byte
  900. private bool buf_dirty; // true if buffer has been written to
  901. private long buf_start; // location of buffer in file
  902. private string name = "[Unknown]"; // name of file.
  903. IntPtr handle; // handle to underlying file
  904. SafeFileHandle safeHandle; // set only when using one of the
  905. // constructors taking SafeFileHandle
  906. }
  907. }