2
0

FileStream.cs 30 KB

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