FileStream.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  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 MOONLIGHT
  89. // default the browser to 'all' anonymous files and let other usage (like smcs) with 'normal'
  90. // (i.e. non-anonymous except for isolated storage) files and paths
  91. this.anonymous = SecurityManager.SecurityEnabled;
  92. #else
  93. this.anonymous = false;
  94. #endif
  95. if (isZeroSize)
  96. bufferSize = 1;
  97. InitBuffer (bufferSize);
  98. if (canseek) {
  99. buf_start = MonoIO.Seek (handle, 0, SeekOrigin.Current, out error);
  100. if (error != MonoIOError.ERROR_SUCCESS) {
  101. throw MonoIO.GetException (name, error);
  102. }
  103. }
  104. /* Can't set append mode */
  105. this.append_startpos=0;
  106. }
  107. // construct from filename
  108. public FileStream (string path, FileMode mode)
  109. : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.Read, DefaultBufferSize, false, FileOptions.None)
  110. {
  111. }
  112. public FileStream (string path, FileMode mode, FileAccess access)
  113. : this (path, mode, access, access == FileAccess.Write ? FileShare.None : FileShare.Read, DefaultBufferSize, false, false)
  114. {
  115. }
  116. public FileStream (string path, FileMode mode, FileAccess access, FileShare share)
  117. : this (path, mode, access, share, DefaultBufferSize, false, FileOptions.None)
  118. {
  119. }
  120. public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
  121. : this (path, mode, access, share, bufferSize, false, FileOptions.None)
  122. {
  123. }
  124. public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
  125. : this (path, mode, access, share, bufferSize, useAsync, FileOptions.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. Exception exc = null;
  733. if (handle != MonoIO.InvalidHandle) {
  734. try {
  735. FlushBuffer ();
  736. } catch (Exception e) {
  737. exc = e;
  738. }
  739. if (owner) {
  740. MonoIOError error;
  741. MonoIO.Close (handle, out error);
  742. if (error != MonoIOError.ERROR_SUCCESS) {
  743. // don't leak the path information for isolated storage
  744. throw MonoIO.GetException (GetSecureFileName (name), error);
  745. }
  746. handle = MonoIO.InvalidHandle;
  747. }
  748. }
  749. canseek = false;
  750. access = 0;
  751. if (disposing && buf != null) {
  752. if (buf.Length == DefaultBufferSize && buf_recycle == null) {
  753. lock (buf_recycle_lock) {
  754. if (buf_recycle == null) {
  755. buf_recycle = buf;
  756. }
  757. }
  758. }
  759. buf = null;
  760. GC.SuppressFinalize (this);
  761. }
  762. if (exc != null)
  763. throw exc;
  764. }
  765. #if !NET_2_1
  766. public FileSecurity GetAccessControl ()
  767. {
  768. throw new NotImplementedException ();
  769. }
  770. public void SetAccessControl (FileSecurity fileSecurity)
  771. {
  772. throw new NotImplementedException ();
  773. }
  774. #endif
  775. // private.
  776. // ReadSegment, WriteSegment, FlushBuffer,
  777. // RefillBuffer and ReadData should only be called
  778. // when the Monitor lock is held, but these methods
  779. // grab it again just to be safe.
  780. private int ReadSegment (byte [] dest, int dest_offset, int count)
  781. {
  782. if (count > buf_length - buf_offset) {
  783. count = buf_length - buf_offset;
  784. }
  785. if (count > 0) {
  786. Buffer.BlockCopy (buf, buf_offset,
  787. dest, dest_offset,
  788. count);
  789. buf_offset += count;
  790. }
  791. return(count);
  792. }
  793. private int WriteSegment (byte [] src, int src_offset,
  794. int count)
  795. {
  796. if (count > buf_size - buf_offset) {
  797. count = buf_size - buf_offset;
  798. }
  799. if (count > 0) {
  800. Buffer.BlockCopy (src, src_offset,
  801. buf, buf_offset,
  802. count);
  803. buf_offset += count;
  804. if (buf_offset > buf_length) {
  805. buf_length = buf_offset;
  806. }
  807. buf_dirty = true;
  808. }
  809. return(count);
  810. }
  811. void FlushBuffer (Stream st)
  812. {
  813. if (buf_dirty) {
  814. MonoIOError error;
  815. if (CanSeek == true) {
  816. MonoIO.Seek (handle, buf_start,
  817. SeekOrigin.Begin,
  818. out error);
  819. if (error != MonoIOError.ERROR_SUCCESS) {
  820. // don't leak the path information for isolated storage
  821. throw MonoIO.GetException (GetSecureFileName (name), error);
  822. }
  823. }
  824. if (st == null) {
  825. int wcount = buf_length;
  826. int offset = 0;
  827. while (wcount > 0){
  828. int n = MonoIO.Write (handle, buf, 0, buf_length, out error);
  829. if (error != MonoIOError.ERROR_SUCCESS) {
  830. // don't leak the path information for isolated storage
  831. throw MonoIO.GetException (GetSecureFileName (name), error);
  832. }
  833. wcount -= n;
  834. offset += n;
  835. }
  836. } else {
  837. st.Write (buf, 0, buf_length);
  838. }
  839. }
  840. buf_start += buf_offset;
  841. buf_offset = buf_length = 0;
  842. buf_dirty = false;
  843. }
  844. private void FlushBuffer ()
  845. {
  846. FlushBuffer (null);
  847. }
  848. private void FlushBufferIfDirty ()
  849. {
  850. if (buf_dirty)
  851. FlushBuffer (null);
  852. }
  853. private void RefillBuffer ()
  854. {
  855. FlushBuffer (null);
  856. buf_length = ReadData (handle, buf, 0,
  857. buf_size);
  858. }
  859. private int ReadData (IntPtr handle, byte[] buf, int offset,
  860. int count)
  861. {
  862. MonoIOError error;
  863. int amount = 0;
  864. /* when async == true, if we get here we don't suport AIO or it's disabled
  865. * and we're using the threadpool */
  866. amount = MonoIO.Read (handle, buf, offset, count, out error);
  867. if (error == MonoIOError.ERROR_BROKEN_PIPE) {
  868. amount = 0; // might not be needed, but well...
  869. } else if (error != MonoIOError.ERROR_SUCCESS) {
  870. // don't leak the path information for isolated storage
  871. throw MonoIO.GetException (GetSecureFileName (name), error);
  872. }
  873. /* Check for read error */
  874. if(amount == -1) {
  875. throw new IOException ();
  876. }
  877. return(amount);
  878. }
  879. void InitBuffer (int size)
  880. {
  881. if (size <= 0)
  882. throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
  883. size = Math.Max (size, 8);
  884. //
  885. // Instead of allocating a new default buffer use the
  886. // last one if there is any available
  887. //
  888. if (size <= DefaultBufferSize && buf_recycle != null) {
  889. lock (buf_recycle_lock) {
  890. if (buf_recycle != null) {
  891. buf = buf_recycle;
  892. buf_recycle = null;
  893. }
  894. }
  895. }
  896. if (buf == null)
  897. buf = new byte [size];
  898. else
  899. Array.Clear (buf, 0, size);
  900. buf_size = size;
  901. // buf_start = 0;
  902. // buf_offset = buf_length = 0;
  903. // buf_dirty = false;
  904. }
  905. private string GetSecureFileName (string filename)
  906. {
  907. return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
  908. }
  909. private string GetSecureFileName (string filename, bool full)
  910. {
  911. return (anonymous) ? Path.GetFileName (filename) :
  912. (full) ? Path.GetFullPath (filename) : filename;
  913. }
  914. // fields
  915. internal const int DefaultBufferSize = 8192;
  916. // Input buffer ready for recycling
  917. static byte[] buf_recycle;
  918. static readonly object buf_recycle_lock = new object ();
  919. private FileAccess access;
  920. private bool owner;
  921. private bool async;
  922. private bool canseek;
  923. private long append_startpos;
  924. private bool anonymous;
  925. private byte [] buf; // the buffer
  926. private int buf_size; // capacity in bytes
  927. private int buf_length; // number of valid bytes in buffer
  928. private int buf_offset; // position of next byte
  929. private bool buf_dirty; // true if buffer has been written to
  930. private long buf_start; // location of buffer in file
  931. private string name = "[Unknown]"; // name of file.
  932. IntPtr handle; // handle to underlying file
  933. SafeFileHandle safeHandle; // set only when using one of the
  934. // constructors taking SafeFileHandle
  935. }
  936. }