FileStream.cs 32 KB

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