SafeFileStream.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. using System;
  2. using System.IO;
  3. using Wayne.Lib.IO.UnitTest;
  4. namespace Wayne.Lib.IO
  5. {
  6. /// <summary>
  7. /// A file writing stream that ensures that the files remain consistent even when a writing operation is interrupted.
  8. /// The writing will be performed to a temporary file that will be exchanged with the target file when the writing has
  9. /// completed. There is a static method, Cleanup that should be called when a program starts up that will clean up and
  10. /// restore the files in the best possible state.
  11. /// </summary>
  12. public class SafeFileWritingStream : Stream
  13. {
  14. #region Fields
  15. private readonly IFileSupport fileSupport;
  16. private readonly SafeFileWritingInterruptPoint interruptAtStage = SafeFileWritingInterruptPoint.DontInterrupt;
  17. private readonly SafeFileInfo safeFileName;
  18. private readonly Stream targetFile;
  19. private readonly Stream tempOutputFile;
  20. private bool closed;
  21. #endregion
  22. #region Construction
  23. /// <summary>
  24. /// Creates a new instance of te SafeFileWriting Stream for the specified file.
  25. /// </summary>
  26. /// <param name="fileName"></param>
  27. /// <exception cref="SafeFileWritingIOException">If some of the files that should be not is accessible.</exception>
  28. [Obsolete("Use constructor taking IFilesupport parameter.")]
  29. public SafeFileWritingStream(string fileName)
  30. : this(FileSupport.fileSupport, fileName, SafeFileWritingInterruptPoint.DontInterrupt)
  31. {
  32. }
  33. /// <summary>
  34. /// Creates a new instance of te SafeFileWriting Stream for the specified file.
  35. /// </summary>
  36. /// <param name="fileSupport">The filesupport implementation to use.</param>
  37. /// <param name="fileName"></param>
  38. /// <exception cref="SafeFileWritingIOException">If some of the files that should be not is accessible.</exception>
  39. public SafeFileWritingStream(IFileSupport fileSupport, string fileName)
  40. : this(fileSupport, fileName, SafeFileWritingInterruptPoint.DontInterrupt)
  41. {
  42. }
  43. /// <summary>
  44. /// Private constuctor used for unit testing.
  45. /// </summary>
  46. /// <param name="fileSupport">The filesupport implementation to use.</param>
  47. /// <param name="fileName"></param>
  48. /// <param name="interruptAtStage"></param>
  49. private SafeFileWritingStream(IFileSupport fileSupport, string fileName, SafeFileWritingInterruptPoint interruptAtStage)
  50. {
  51. fileName = Paths.Parse(fileName);
  52. this.fileSupport = fileSupport;
  53. this.interruptAtStage = interruptAtStage;
  54. SetWritingStage(SafeFileWritingInterruptPoint.WritingNotBegun);
  55. safeFileName = SafeFileInfo.FromOriginalFileName(fileName);
  56. try
  57. {
  58. if (fileSupport.FileExists(fileName))
  59. targetFile = fileSupport.Open(fileName, FileMode.Open, FileAccess.Write, FileShare.Read);
  60. }
  61. catch (IOException ioException)
  62. {
  63. throw new SafeFileWritingIOException("Error opening target file (" + fileName + ")", ioException);
  64. }
  65. //If there is an -old file try to delete it, otherwise it is ok for the File.Delete to throw.
  66. if (fileSupport.FileExists(safeFileName.OldFileName))
  67. {
  68. try
  69. {
  70. fileSupport.Delete(safeFileName.OldFileName);
  71. }
  72. catch (IOException ioException)
  73. {
  74. throw new SafeFileWritingIOException("Error deleting a -old file (" + safeFileName.OldFileName + ")", ioException);
  75. }
  76. }
  77. try
  78. {
  79. tempOutputFile = fileSupport.Open(safeFileName.TempFileName, FileMode.Create, FileAccess.Write, FileShare.None);
  80. }
  81. catch (IOException ioException)
  82. {
  83. throw new SafeFileWritingIOException("Error opening the temp file (" + safeFileName.TempFileName + ")", ioException);
  84. }
  85. SetWritingStage(SafeFileWritingInterruptPoint.WritingOngoing);
  86. }
  87. #endregion
  88. #region Properties
  89. /// <summary>
  90. /// Always false, SafeFileStream is write-only
  91. /// </summary>
  92. public override bool CanRead
  93. {
  94. get { return false; }
  95. }
  96. /// <summary>
  97. /// Always false, SafeFileStream is write-only
  98. /// </summary>
  99. public override bool CanSeek
  100. {
  101. get { return false; }
  102. }
  103. /// <summary>
  104. /// Always true, SafeFileStream is write-only
  105. /// </summary>
  106. public override bool CanWrite
  107. {
  108. get { return true; }
  109. }
  110. /// <summary>
  111. /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
  112. /// </summary>
  113. /// <exception cref="ObjectDisposedException">The stream is closed.</exception>
  114. /// <exception cref="IOException">An I/O error occurs.</exception>
  115. public override void Flush()
  116. {
  117. tempOutputFile.Flush();
  118. }
  119. /// <summary>
  120. /// Gets the length in bytes of the stream.
  121. /// </summary>
  122. /// <exception cref="NotSupportedException">CanSeek for this stream is false.</exception>
  123. /// <exception cref="IOException">An I/O error occurs, such as the file being closed.</exception>
  124. public override long Length
  125. {
  126. get { return tempOutputFile.Length; }
  127. }
  128. /// <summary>
  129. /// Gets or sets the current position of this stream.
  130. /// </summary>
  131. /// <exception cref="NotSupportedException">The stream does not support seeking.</exception>
  132. public override long Position
  133. {
  134. get
  135. {
  136. return tempOutputFile.Position;
  137. }
  138. set
  139. {
  140. throw new NotSupportedException();
  141. }
  142. }
  143. #endregion
  144. #region Methods
  145. /// <summary>
  146. /// Not supported
  147. /// </summary>
  148. /// <param name="buffer"></param>
  149. /// <param name="offset"></param>
  150. /// <param name="count"></param>
  151. /// <returns></returns>
  152. /// <exception cref="NotSupportedException">Always</exception>
  153. public override int Read(byte[] buffer, int offset, int count)
  154. {
  155. throw new NotSupportedException();
  156. }
  157. /// <summary>
  158. /// Not supported. Stream is Write-only.
  159. /// </summary>
  160. /// <param name="offset"></param>
  161. /// <param name="origin"></param>
  162. /// <returns></returns>
  163. /// <exception cref="NotSupportedException">Always.</exception>
  164. public override long Seek(long offset, SeekOrigin origin)
  165. {
  166. throw new NotSupportedException();
  167. }
  168. /// <summary>
  169. /// Not supported. Fast-forward writing only.
  170. /// </summary>
  171. /// <param name="value"></param>
  172. public override void SetLength(long value)
  173. {
  174. throw new NotSupportedException();
  175. }
  176. /// <summary>
  177. /// Writes a block of bytes to this stream using data from a buffer.
  178. /// </summary>
  179. /// <param name="buffer">The buffer containing data to write to the stream.</param>
  180. /// <param name="offset">The zero-based byte offset in array at which to begin copying bytes to the current stream.</param>
  181. /// <param name="count">The maximum number of bytes to be written to the current stream.</param>
  182. /// <exception cref="ArgumentNullException">array is null.</exception>
  183. /// <exception cref="ObjectDisposedException">The stream is closed.</exception>
  184. /// <exception cref="IOException">An I/O error occurs.</exception>
  185. /// <exception cref="ArgumentException">offset and count describe an invalid range in array.</exception>
  186. /// <exception cref="ArgumentOutOfRangeException">offset or count is negative.</exception>
  187. public override void Write(byte[] buffer, int offset, int count)
  188. {
  189. tempOutputFile.Write(buffer, offset, count);
  190. }
  191. /// <summary>
  192. /// Closes the stream and overwrites the target file.
  193. /// </summary>
  194. public override void Close()
  195. {
  196. base.Close();
  197. if (!closed)
  198. {
  199. closed = true;
  200. //Close the temporary file.
  201. tempOutputFile.Close();
  202. //Unlock the original file.
  203. if (targetFile != null)
  204. {
  205. targetFile.Close();
  206. //Rename the original file to .old
  207. fileSupport.Move(safeFileName.OriginalFileName, safeFileName.OldFileName, 100, 100);
  208. SetWritingStage(SafeFileWritingInterruptPoint.WritingCompleteOriginalFileRenamedToOld);
  209. }
  210. //Change name on the temporary file to the target file name
  211. fileSupport.Move(safeFileName.TempFileName, safeFileName.OriginalFileName, 100, 100);
  212. SetWritingStage(SafeFileWritingInterruptPoint.WritingCompleteTempFileRenamedToTargetFile);
  213. if (targetFile != null)
  214. {
  215. //Delete the old file
  216. fileSupport.Delete(safeFileName.OldFileName, 100, 100);
  217. SetWritingStage(SafeFileWritingInterruptPoint.WritingComplete);
  218. }
  219. }
  220. }
  221. /// <summary>
  222. /// Private method that is used to enable interrupts in different phases of the writing
  223. /// for the unit testing.
  224. /// </summary>
  225. /// <param name="writingStage"></param>
  226. private void SetWritingStage(SafeFileWritingInterruptPoint writingStage)
  227. {
  228. if (writingStage == interruptAtStage)
  229. {
  230. targetFile.Close();
  231. tempOutputFile.Close();
  232. throw new SafeFileWritingInterruptedException();
  233. }
  234. }
  235. #endregion
  236. #region Static Methods
  237. /// <summary>
  238. /// All file types that is written with the SafeFileWritingStream should be cleaned at certain points
  239. /// to maintain the integrity. The typical place to place a call to this method is at the startup of
  240. /// a module. If the module wrote something and was interrupted by a program shutdown, it can rescue some data with this
  241. /// method.
  242. /// </summary>
  243. /// <param name="folderPath"></param>
  244. /// <param name="pattern"></param>
  245. /// <param name="temporaryFileFoundCallback">Delegate that is called when a temp file is found and asks for action to take. This delegate may be invoked several times.</param>
  246. /// <param name="userToken">Token that is returned in the invokation of the temporaryFileFoundCallback.</param>
  247. /// <exception cref="ArgumentException">Folder does not exist</exception>
  248. [Obsolete("Use Cleanup method supplying file support.")]
  249. public static void Cleanup(string folderPath, string pattern, EventHandler<SafeFileWritingCleanupEventArgs> temporaryFileFoundCallback, object userToken)
  250. {
  251. Cleanup(FileSupport.fileSupport, folderPath, pattern, temporaryFileFoundCallback, userToken);
  252. }
  253. /// <summary>
  254. /// All file types that is written with the SafeFileWritingStream should be cleaned at certain points
  255. /// to maintain the integrity. The typical place to place a call to this method is at the startup of
  256. /// a module. If the module wrote something and was interrupted by a program shutdown, it can rescue some data with this
  257. /// method.
  258. /// </summary>
  259. /// <param name="fileSupport">The filesupport implementation to use.</param>
  260. /// <param name="folderPath"></param>
  261. /// <param name="pattern"></param>
  262. /// <param name="temporaryFileFoundCallback">Delegate that is called when a temp file is found and asks for action to take. This delegate may be invoked several times.</param>
  263. /// <param name="userToken">Token that is returned in the invokation of the temporaryFileFoundCallback.</param>
  264. public static void Cleanup(IFileSupport fileSupport, string folderPath, string pattern, EventHandler<SafeFileWritingCleanupEventArgs> temporaryFileFoundCallback, object userToken)
  265. {
  266. if (fileSupport.DirectoryExists(folderPath))
  267. {
  268. foreach (SafeFileInfo safeFile in SafeFileInfo.GetFiles(fileSupport, folderPath, pattern))
  269. {
  270. //Stage 0 - No writing has been interrupted.
  271. if (safeFile.OriginalFileExists && !safeFile.TempFileExists && !safeFile.OldFileExist)
  272. {
  273. //Do nothing
  274. }
  275. //Stage 1 - Writing has been done, the Temp file has been created, and a undefined percentage of the file has been written.
  276. else if ((safeFile.OriginalFileExists && safeFile.TempFileExists) || //Overwrite scenario
  277. (!safeFile.OriginalFileExists && !safeFile.OldFileExist && safeFile.TempFileExists)) //Create new file scenario
  278. {
  279. //Remove the Temp file and send event log with the content of the temp file.
  280. fileSupport.Delete(safeFile.TempFileName);
  281. SafeFileWritingCleanupEventArgs evArgs = new SafeFileWritingCleanupEventArgs(safeFile.TempFileName, userToken);
  282. if (temporaryFileFoundCallback != null)
  283. temporaryFileFoundCallback(null, evArgs);
  284. if (evArgs.Action == SafeFileWritingCleanupAction.StoreInRestoredTempFileDir)
  285. {
  286. string restoredTempFilesDir = Paths.Combine("RestoredTemp");
  287. fileSupport.EnsureDirectoryExists(restoredTempFilesDir);
  288. string newFileName = string.Concat(Guid.NewGuid(), Path.GetFileName(safeFile.TempFileName));
  289. fileSupport.Move(safeFile.TempFileName, Path.Combine(restoredTempFilesDir, newFileName), 100, 100);
  290. }
  291. else
  292. {
  293. fileSupport.Delete(safeFile.TempFileName);
  294. }
  295. }
  296. //Stage 2- Writing has been completed, The original file has been renamed to old.
  297. else if (safeFile.TempFileExists && safeFile.OldFileExist)
  298. {
  299. //Remove the Old file
  300. fileSupport.Delete(safeFile.OldFileName);
  301. //...and make the temp file the real file.
  302. fileSupport.Move(safeFile.TempFileName, safeFile.OriginalFileName, 100, 100);
  303. }
  304. //Stage 3 - Temp file has been sucessfully renamed but old file still remains.
  305. else if (safeFile.OriginalFileExists && safeFile.OldFileExist)
  306. {
  307. fileSupport.Delete(safeFile.OldFileName);
  308. }
  309. }
  310. }
  311. }
  312. #endregion
  313. }
  314. }