FileStream.cs 33 KB

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