FileStream.cs 31 KB

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