FileStream.cs 32 KB

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