FileStream.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. //
  2. // System.IO/FileStream.cs
  3. //
  4. // Authors:
  5. // Dietmar Maurer ([email protected])
  6. // Dan Lewis ([email protected])
  7. //
  8. // (C) 2001 Ximian, Inc. http://www.ximian.com
  9. //
  10. using System;
  11. using System.Runtime.CompilerServices;
  12. // FIXME: emit the correct exceptions everywhere. add error handling.
  13. namespace System.IO
  14. {
  15. public class FileStream : Stream
  16. {
  17. // construct from handle
  18. public FileStream (IntPtr handle, FileAccess access)
  19. : this (handle, access, true, DefaultBufferSize, false) {}
  20. public FileStream (IntPtr handle, FileAccess access, bool ownsHandle)
  21. : this (handle, access, ownsHandle, DefaultBufferSize, false) {}
  22. public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
  23. : this (handle, access, ownsHandle, bufferSize, false) {}
  24. public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
  25. {
  26. this.handle = handle;
  27. this.access = access;
  28. this.owner = ownsHandle;
  29. this.async = isAsync;
  30. MonoIOError error;
  31. if(MonoIO.GetFileType (handle, out error) ==
  32. MonoFileType.Disk) {
  33. this.canseek = true;
  34. } else {
  35. this.canseek = false;
  36. }
  37. InitBuffer (bufferSize);
  38. /* Can't set append mode */
  39. this.append_startpos=0;
  40. }
  41. // construct from filename
  42. public FileStream (string name, FileMode mode)
  43. : this (name, mode, FileAccess.ReadWrite, FileShare.ReadWrite, DefaultBufferSize, false) { }
  44. public FileStream (string name, FileMode mode, FileAccess access)
  45. : this (name, mode, access, FileShare.ReadWrite, DefaultBufferSize, false) { }
  46. public FileStream (string name, FileMode mode, FileAccess access, FileShare share)
  47. : this (name, mode, access, share, DefaultBufferSize, false) { }
  48. public FileStream (string name, FileMode mode, FileAccess access, FileShare share, int bufferSize)
  49. : this (name, mode, access, share, bufferSize, false) { }
  50. public FileStream (string name, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool isAsync)
  51. {
  52. if (name == null) {
  53. throw new ArgumentNullException ("Name is null");
  54. }
  55. if (name == "") {
  56. throw new ArgumentException ("Name is empty");
  57. }
  58. if (name.IndexOfAny (Path.InvalidPathChars) != -1) {
  59. throw new ArgumentException ("Name has invalid chars");
  60. }
  61. if (Directory.Exists (name)) {
  62. throw new UnauthorizedAccessException ("Access to the path '" + Path.GetFullPath (name) + "' is denied.");
  63. }
  64. /* Append streams can't be read (see FileMode
  65. * docs)
  66. */
  67. if (mode==FileMode.Append &&
  68. (access&FileAccess.Read)==FileAccess.Read) {
  69. throw new ArgumentException("Append streams can not be read");
  70. }
  71. this.name = name;
  72. // TODO: demand permissions
  73. MonoIOError error;
  74. this.handle = MonoIO.Open (name, mode, access, share,
  75. out error);
  76. if (handle == MonoIO.InvalidHandle) {
  77. throw MonoIO.GetException (name, error);
  78. }
  79. this.access = access;
  80. this.owner = true;
  81. this.async = isAsync;
  82. /* Can we open non-files by name? */
  83. if (MonoIO.GetFileType (handle, out error) ==
  84. MonoFileType.Disk) {
  85. this.canseek = true;
  86. } else {
  87. this.canseek = false;
  88. }
  89. InitBuffer (bufferSize);
  90. if (mode==FileMode.Append) {
  91. this.Seek (0, SeekOrigin.End);
  92. this.append_startpos=this.Position;
  93. } else {
  94. this.append_startpos=0;
  95. }
  96. }
  97. // properties
  98. public override bool CanRead {
  99. get {
  100. return access == FileAccess.Read ||
  101. access == FileAccess.ReadWrite;
  102. }
  103. }
  104. public override bool CanWrite {
  105. get {
  106. return access == FileAccess.Write ||
  107. access == FileAccess.ReadWrite;
  108. }
  109. }
  110. public override bool CanSeek {
  111. get {
  112. return(canseek);
  113. }
  114. }
  115. public virtual bool IsAsync {
  116. get {
  117. return (async);
  118. }
  119. }
  120. public string Name {
  121. get {
  122. return name;
  123. }
  124. }
  125. public override long Length {
  126. get {
  127. MonoIOError error;
  128. return MonoIO.GetLength (handle, out error);
  129. }
  130. }
  131. public override long Position {
  132. get {
  133. if(CanSeek == false) {
  134. throw new NotSupportedException("The stream does not support seeking");
  135. }
  136. lock(this) {
  137. return(buf_start + buf_offset);
  138. }
  139. }
  140. set {
  141. if(CanSeek == false) {
  142. throw new NotSupportedException("The stream does not support seeking");
  143. }
  144. if(value < 0) {
  145. throw new ArgumentOutOfRangeException("Attempt to set the position to a negative value");
  146. }
  147. Seek (value, SeekOrigin.Begin);
  148. }
  149. }
  150. public virtual IntPtr Handle {
  151. get { return handle; }
  152. }
  153. // methods
  154. public override int ReadByte ()
  155. {
  156. lock(this) {
  157. if (buf_offset >= buf_length) {
  158. RefillBuffer ();
  159. if (buf_length == 0) {
  160. return -1;
  161. }
  162. }
  163. return(buf [buf_offset ++]);
  164. }
  165. }
  166. public override void WriteByte (byte value)
  167. {
  168. lock(this) {
  169. if (buf_offset == buf_size) {
  170. FlushBuffer ();
  171. }
  172. buf [buf_offset ++] = value;
  173. if (buf_offset > buf_length) {
  174. buf_length = buf_offset;
  175. }
  176. buf_dirty = true;
  177. }
  178. }
  179. public override int Read (byte[] dest, int dest_offset, int count)
  180. {
  181. int copied = 0;
  182. lock(this) {
  183. int n = ReadSegment (dest, dest_offset, count);
  184. copied += n;
  185. count -= n;
  186. if (count == 0) {
  187. /* If there was already enough
  188. * buffered, no need to read
  189. * more from the file.
  190. */
  191. return (copied);
  192. }
  193. if (count > buf_size) {
  194. /* Read as much as we can, up
  195. * to count bytes
  196. */
  197. FlushBuffer();
  198. n = ReadData (handle, dest,
  199. dest_offset+copied,
  200. count);
  201. /* Make the next buffer read
  202. * start from the right place
  203. */
  204. buf_start += n;
  205. } else {
  206. RefillBuffer ();
  207. n = ReadSegment (dest,
  208. dest_offset+copied,
  209. count);
  210. }
  211. copied += n;
  212. return(copied);
  213. }
  214. }
  215. public override void Write (byte[] src, int src_offset, int count)
  216. {
  217. int copied = 0;
  218. lock(this) {
  219. while (count > 0) {
  220. int n = WriteSegment (src, src_offset + copied, count);
  221. copied += n;
  222. count -= n;
  223. FlushBuffer ();
  224. if (count == 0) {
  225. break;
  226. }
  227. if (count > buf_size) {
  228. // shortcut for long writes
  229. MonoIOError error;
  230. MonoIO.Write (handle, src, src_offset + copied, count, out error);
  231. buf_start += count;
  232. break;
  233. }
  234. }
  235. }
  236. }
  237. public override long Seek (long offset, SeekOrigin origin)
  238. {
  239. long pos;
  240. // make absolute
  241. if(CanSeek == false) {
  242. throw new NotSupportedException("The stream does not support seeking");
  243. }
  244. lock(this) {
  245. switch (origin) {
  246. case SeekOrigin.End:
  247. pos = Length + offset;
  248. break;
  249. case SeekOrigin.Current:
  250. pos = Position + offset;
  251. break;
  252. case SeekOrigin.Begin: default:
  253. pos = offset;
  254. break;
  255. }
  256. if (pos < 0) {
  257. /* LAMESPEC: shouldn't this be
  258. * ArgumentOutOfRangeException?
  259. */
  260. throw new ArgumentException("Attempted to Seek before the beginning of the stream");
  261. }
  262. if(pos < this.append_startpos) {
  263. /* More undocumented crap */
  264. throw new IOException("Can't seek back over pre-existing data in append mode");
  265. }
  266. if (pos >= buf_start &&
  267. pos <= buf_start + buf_length) {
  268. buf_offset = (int) (pos - buf_start);
  269. return pos;
  270. }
  271. FlushBuffer ();
  272. MonoIOError error;
  273. buf_start = MonoIO.Seek (handle, pos,
  274. SeekOrigin.Begin,
  275. out error);
  276. return(buf_start);
  277. }
  278. }
  279. public override void SetLength (long length)
  280. {
  281. if(CanSeek == false) {
  282. throw new NotSupportedException("The stream does not support seeking");
  283. }
  284. if(CanWrite == false) {
  285. throw new NotSupportedException("The stream does not support writing");
  286. }
  287. if(length < 0) {
  288. throw new ArgumentOutOfRangeException("Length is less than 0");
  289. }
  290. Flush ();
  291. MonoIOError error;
  292. MonoIO.SetLength (handle, length, out error);
  293. }
  294. public override void Flush ()
  295. {
  296. lock(this) {
  297. FlushBuffer ();
  298. }
  299. // The flushing is not actually required, in
  300. //the mono runtime we were mapping flush to
  301. //`fsync' which is not the same.
  302. //
  303. //MonoIO.Flush (handle);
  304. }
  305. public override void Close ()
  306. {
  307. Dispose (true);
  308. GC.SuppressFinalize (this); // remove from finalize queue
  309. }
  310. // protected
  311. ~FileStream ()
  312. {
  313. Dispose (false);
  314. }
  315. protected virtual void Dispose (bool disposing) {
  316. if (owner && handle != MonoIO.InvalidHandle) {
  317. lock(this) {
  318. FlushBuffer ();
  319. }
  320. MonoIOError error;
  321. MonoIO.Close (handle, out error);
  322. handle = MonoIO.InvalidHandle;
  323. }
  324. if (disposing) {
  325. buf = null;
  326. }
  327. }
  328. // private.
  329. // ReadSegment, WriteSegment, FlushBuffer,
  330. // RefillBuffer and ReadData should only be called
  331. // when the Monitor lock is held, but these methods
  332. // grab it again just to be safe.
  333. private int ReadSegment (byte [] dest, int dest_offset,
  334. int count)
  335. {
  336. lock(this) {
  337. if (count > buf_length - buf_offset) {
  338. count = buf_length - buf_offset;
  339. }
  340. if (count > 0) {
  341. Buffer.BlockCopy (buf, buf_offset,
  342. dest, dest_offset,
  343. count);
  344. buf_offset += count;
  345. }
  346. return(count);
  347. }
  348. }
  349. private int WriteSegment (byte [] src, int src_offset,
  350. int count)
  351. {
  352. lock(this) {
  353. if (count > buf_size - buf_offset) {
  354. count = buf_size - buf_offset;
  355. }
  356. if (count > 0) {
  357. Buffer.BlockCopy (src, src_offset,
  358. buf, buf_offset,
  359. count);
  360. buf_offset += count;
  361. if (buf_offset > buf_length) {
  362. buf_length = buf_offset;
  363. }
  364. buf_dirty = true;
  365. }
  366. return(count);
  367. }
  368. }
  369. private void FlushBuffer ()
  370. {
  371. lock(this) {
  372. if (buf_dirty) {
  373. MonoIOError error;
  374. if (CanSeek == true) {
  375. MonoIO.Seek (handle, buf_start,
  376. SeekOrigin.Begin,
  377. out error);
  378. }
  379. MonoIO.Write (handle, buf, 0,
  380. buf_length, out error);
  381. }
  382. buf_start += buf_length;
  383. buf_offset = buf_length = 0;
  384. buf_dirty = false;
  385. }
  386. }
  387. private void RefillBuffer ()
  388. {
  389. lock(this) {
  390. FlushBuffer();
  391. buf_length = ReadData (handle, buf, 0,
  392. buf_size);
  393. }
  394. }
  395. private int ReadData (IntPtr handle, byte[] buf, int offset,
  396. int count)
  397. {
  398. MonoIOError error;
  399. lock(this) {
  400. int amount = MonoIO.Read (handle, buf, offset,
  401. count, out error);
  402. /* Check for read error */
  403. if(amount == -1) {
  404. /* Kludge around broken pipes */
  405. if(error == MonoIOError.ERROR_BROKEN_PIPE) {
  406. amount = 0;
  407. } else {
  408. throw new IOException ();
  409. }
  410. }
  411. return(amount);
  412. }
  413. }
  414. private void InitBuffer (int size)
  415. {
  416. if (size < 0)
  417. throw new ArgumentOutOfRangeException ("Buffer size cannot be negative.");
  418. if (size < 8)
  419. size = 8;
  420. buf = new byte [size];
  421. buf_size = size;
  422. buf_start = 0;
  423. buf_offset = buf_length = 0;
  424. buf_dirty = false;
  425. }
  426. // fields
  427. private static int DefaultBufferSize = 8192;
  428. private FileAccess access;
  429. private bool owner;
  430. private bool async;
  431. private bool canseek;
  432. private long append_startpos;
  433. private byte [] buf; // the buffer
  434. private int buf_size; // capacity in bytes
  435. private int buf_length; // number of valid bytes in buffer
  436. private int buf_offset; // position of next byte
  437. private bool buf_dirty; // true if buffer has been written to
  438. private long buf_start; // location of buffer in file
  439. private string name = "[Unknown]"; // name of file.
  440. IntPtr handle; // handle to underlying file
  441. }
  442. }