ExcelBinaryWriter.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. namespace Biff8Excel.Excel
  6. {
  7. internal class ExcelBinaryWriter : BinaryWriter, IDisposable
  8. {
  9. //static int tmp ; //用于tmp文件不重覆
  10. string m_FileName;
  11. public ExcelBinaryWriter()
  12. {
  13. //m_FileName = "btw" + tmp.ToString() + ".tmp";
  14. //tmp++;
  15. //生成一临时文件
  16. m_FileName = Path.GetTempFileName();
  17. FileInfo myFileInfo = new FileInfo(m_FileName);
  18. myFileInfo.Attributes = FileAttributes.Temporary;
  19. }
  20. public long Length
  21. {
  22. get
  23. {
  24. //StreamWriter myWriter = File.AppendText(m_FileName);
  25. if (!OutStream.CanRead)
  26. OutStream = File.Open(m_FileName, FileMode.Open);
  27. return this.OutStream.Length;
  28. }
  29. }
  30. public long Position
  31. {
  32. get
  33. {
  34. if (OutStream.CanRead)
  35. return OutStream.Position;
  36. return 0;
  37. }
  38. set
  39. {
  40. if (!OutStream.CanWrite)
  41. OutStream = File.Open(m_FileName, FileMode.Open);
  42. OutStream.Position = value;
  43. }
  44. }
  45. public byte[] Stream
  46. {
  47. get
  48. {
  49. if (OutStream == System.IO.Stream.Null)
  50. return null;
  51. if ( !OutStream.CanRead )
  52. OutStream = File.Open(m_FileName, FileMode.Open);
  53. int rdlen = (int)this.OutStream.Length;
  54. byte[] b = new byte[rdlen];
  55. this.OutStream.Seek(0, SeekOrigin.Begin);
  56. this.OutStream.Read(b, 0, rdlen);
  57. return b;
  58. }
  59. }
  60. public override void Write(byte[] buffer)
  61. {
  62. if (buffer == null)
  63. return;
  64. int len = buffer.Length;
  65. if (len == 0)
  66. return;
  67. //if (OutStream == System.IO.Stream.Null)
  68. // OutStream = File.Create(fn);
  69. if ( OutStream == System.IO.Stream.Null)
  70. OutStream = File.Open(m_FileName, FileMode.Truncate);
  71. OutStream.Write(buffer, 0, len);
  72. //OutStream.Flush();
  73. }
  74. internal void clear()
  75. {
  76. //删除临时文件
  77. OutStream.Close();
  78. if (File.Exists(m_FileName))
  79. File.Delete(m_FileName);
  80. m_FileName = string.Empty;
  81. }
  82. /// <summary>
  83. /// 删除临时文件
  84. /// </summary>
  85. ~ExcelBinaryWriter()
  86. {
  87. clear();
  88. }
  89. }
  90. }