PageRenderTime 56ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/See.Sharper/Sharper_IO.cs

#
C# | 313 lines | 144 code | 39 blank | 130 comment | 19 complexity | 7d21f361547b72563ad6767bd8e26bc8 MD5 | raw file
Possible License(s): Apache-2.0
  1. #region Copyright & License
  2. /*
  3. Copyright 2009-2010 Stepan Adamec (adamec@yasas.org)
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. #endregion
  15. namespace See.Sharper {
  16. using System;
  17. using System.IO;
  18. using System.Text;
  19. /// <summary>
  20. /// Extensions of frequently used classes in 'System.IO' namespace.
  21. /// </summary>
  22. public static class Sharper_IO {
  23. /// <summary>
  24. /// File name filter used as a default filter for selecting all files.
  25. /// </summary>
  26. public static readonly string ALL_FILES_PATTERN = "*.*";
  27. /// <summary>
  28. /// Size of the byte array used for copying stream content.
  29. /// </summary>
  30. public static readonly int DEFAULT_BUFFER_SIZE = 4096;
  31. #region Directories
  32. /// <summary>
  33. /// Creates the directory represented by DirectoryInfo instance, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
  34. /// </summary>
  35. /// <param name="self"></param>
  36. public static void CreateFully(this DirectoryInfo self) {
  37. if (!self.Parent.Exists) {
  38. self.Parent.CreateFully();
  39. }
  40. self.Create();
  41. }
  42. /// <summary>
  43. /// Executes the <paramref name="action"/> for each file in the parent folder/directory.
  44. /// </summary>
  45. /// <param name="self">Parent folder/directory.</param>
  46. /// <param name="action">Action to be executed.</param>
  47. public static void EachFile(this DirectoryInfo self, Action<FileInfo> action) {
  48. self.EachFile(ALL_FILES_PATTERN, action);
  49. }
  50. /// <summary>
  51. /// Executes the <paramref name="action"/> for each file whose name matches the given pattern in the parent folder/directory.
  52. /// </summary>
  53. /// <param name="self">Parent folder/directory.</param>
  54. /// <param name="pattern">Widlcard pattern used as a file name filter.</param>
  55. /// <param name="action">Action to be executed.</param>
  56. /// <seealso cref="System.IO.DirectoryInfo.GetFiles(String)"/>
  57. public static void EachFile(this DirectoryInfo self, string pattern, Action<FileInfo> action) {
  58. self.GetFiles(pattern).Each<FileInfo>(file => action(file));
  59. }
  60. /// <summary>
  61. /// Executes the <paramref name="action"/> for each file in the parent folder/directory and all descendant folders/directories.
  62. /// Descendant directories are recursively searched in a depth-first fashion.
  63. /// </summary>
  64. /// <param name="self">Parent folder/directory.</param>
  65. /// <param name="action">Action to be executed.</param>
  66. public static void EachFileRecurse(this DirectoryInfo self, Action<FileInfo> action) {
  67. self.EachFileRecurse(ALL_FILES_PATTERN, action);
  68. }
  69. /// <summary>
  70. /// Executes the <paramref name="action"/> for each file whose name matches the given pattern in the parent folder/directory and all descendant folders/directories.
  71. /// Descendant directories are recursively searched in a depth-first fashion.
  72. /// </summary>
  73. /// <param name="self">Parent folder/directory.</param>
  74. /// <param name="pattern">Widlcard pattern used as a file name filter.</param>
  75. /// <param name="action">Action to be executed.</param>
  76. public static void EachFileRecurse(this DirectoryInfo self, string pattern, Action<FileInfo> action) {
  77. self.GetFiles(pattern, SearchOption.AllDirectories).Each<FileInfo>(file => action(file));
  78. }
  79. #endregion
  80. #region Files
  81. /// <summary>
  82. /// Traverse through each byte of this file and executes the <paramref name="action"/> on each byte.
  83. /// </summary>
  84. /// <param name="self">The file.</param>
  85. /// <param name="action">The action to be executed.</param>
  86. public static void EachByte(this FileInfo self, Action<byte> action) {
  87. new FileStream(self.FullName, FileMode.Open, FileAccess.Read).Using(
  88. it => new BufferedStream(it).Using(stream => {
  89. int b;
  90. do {
  91. b = stream.ReadByte();
  92. if (b != -1) {
  93. action((byte)b);
  94. }
  95. } while (b != -1);
  96. })
  97. );
  98. }
  99. /// <summary>
  100. /// Traverse through each line of this file and executes the <paramref name="action"/> on each line.
  101. /// </summary>
  102. /// <param name="self">The file.</param>
  103. /// <param name="action">The action to be executed.</param>
  104. public static void EachLine(this FileInfo self, Action<string> action) {
  105. string line = String.Empty;
  106. self.WithReader(reader => {
  107. do {
  108. line = reader.ReadLine();
  109. if (line != null) {
  110. action(line);
  111. }
  112. } while (line != null);
  113. });
  114. }
  115. /// <summary>
  116. /// Creates a new StreamReader for this file using default encoding and then passes it into the <paramref name="action"/>, ensuring the reader is closed after the action returns.
  117. /// </summary>
  118. /// <param name="self">The file.</param>
  119. /// <param name="action">Action to be executed.</param>
  120. public static void WithReader(this FileInfo self, Action<StreamReader> action) {
  121. self.WithReader(Encoding.Default, action);
  122. }
  123. /// <summary>
  124. /// Creates a new StreamReader for this file and then passes it into the <paramref name="action"/>, ensuring the reader is closed after the action returns.
  125. /// </summary>
  126. /// <param name="self">The file.</param>
  127. /// <param name="encoding">Encoding used to create the stream reader.</param>
  128. /// <param name="action">Action to be executed.</param>
  129. public static void WithReader(this FileInfo self, Encoding encoding, Action<StreamReader> action) {
  130. self.OpenRead().Using(stream => {
  131. try {
  132. new StreamReader(stream, encoding).Using(reader => {
  133. try {
  134. action(reader);
  135. } finally {
  136. reader.CloseQuietly();
  137. }
  138. });
  139. } finally {
  140. stream.CloseQuietly();
  141. }
  142. });
  143. }
  144. #endregion
  145. #region File System Objects
  146. /// <summary>
  147. /// Returns a relative path of a given file system object to the given <paramref name="parent"/>.
  148. /// </summary>
  149. /// <param name="self"></param>
  150. /// <param name="parent">Parent directory specified as FileInfo/DirectoryInfo instance.</param>
  151. /// <returns>Relative path to the given parent.</returns>
  152. public static string GetRelativeName(this FileSystemInfo self, FileSystemInfo parent) {
  153. if (parent == null) {
  154. throw new ArgumentNullException("parent");
  155. }
  156. return self.GetRelativeName(parent.FullName);
  157. }
  158. /// <summary>
  159. /// Returns a relative path of a given file system object to the given <paramref name="parent"/>.
  160. /// <example><code>
  161. /// System.Console.WriteLine(
  162. /// new FileInfo(@"C:\Folder_1\Folder_2\Folder_3\File").GetRelativeName(@"C:\Folder_1")
  163. /// );
  164. /// Output: Folder_2\Folder_3\File
  165. /// </code></example>
  166. /// </summary>
  167. /// <param name="self">The file or directory.</param>
  168. /// <param name="parent">Parent directory specified as string.</param>
  169. /// <returns>Relative path to the given parent.</returns>
  170. public static string GetRelativeName(this FileSystemInfo self, string parent) {
  171. if (parent == null) {
  172. throw new ArgumentNullException("parent");
  173. }
  174. string path = parent;
  175. if (!path.EndsWith(Path.DirectorySeparatorChar.ToString())) {
  176. path = path + Path.DirectorySeparatorChar;
  177. }
  178. if (self.FullName.IndexOf(path) > -1) {
  179. return self.FullName.Substring(path.Length);
  180. }
  181. return self.FullName;
  182. }
  183. #endregion
  184. #region Streams
  185. /// <summary>
  186. /// Copies the content of the stream <paramref name="self"/> to another using default buffer size. Both source and target streams will be closed.
  187. /// </summary>
  188. /// <typeparam name="S">Type of the stream.</typeparam>
  189. /// <param name="self">The source stream.</param>
  190. /// <param name="target">The target stream</param>
  191. public static void CopyTo<S>(this S self, S target) where S : Stream {
  192. self.CopyTo(target, DEFAULT_BUFFER_SIZE, true, true);
  193. }
  194. /// <summary>
  195. /// Copies the content of the stream <paramref name="self"/> to another using the given buffer size. Both source and target streams will be closed.
  196. /// </summary>
  197. /// <typeparam name="S">Type of the stream.</typeparam>
  198. /// <param name="self">The source stream.</param>
  199. /// <param name="target">The target stream</param>
  200. /// <param name="bufferSize">Size of the buffer to be used.</param>
  201. public static void CopyTo<S>(this S self, S target, int bufferSize) where S : Stream {
  202. self.CopyTo(target, bufferSize, true, true);
  203. }
  204. /// <summary>
  205. /// Copies the content of the stream <paramref name="self"/> to another using default buffer size. Source and target streams will be closed depending on the value of a corresponding parameter.
  206. /// </summary>
  207. /// <typeparam name="S">Type of the stream.</typeparam>
  208. /// <param name="self">The source stream.</param>
  209. /// <param name="target">The target stream</param>
  210. /// <param name="closeSelf">Close the source stream <paramref name="self"/> after copying.</param>
  211. /// <param name="closeTarget">Close the <paramref name="target"/> stream after copying.</param>
  212. public static void CopyTo<S>(this S self, S target, bool closeSelf, bool closeTarget) where S : Stream {
  213. self.CopyTo(target, DEFAULT_BUFFER_SIZE, closeSelf, closeTarget);
  214. }
  215. /// <summary>
  216. /// Copies the content of the stream <paramref name="self"/> to another using the given buffer size. Source and target streams will be closed depending on the value of a corresponding parameter.
  217. /// </summary>
  218. /// <typeparam name="S">Type of the stream.</typeparam>
  219. /// <param name="self">The source stream.</param>
  220. /// <param name="target">The target stream</param>
  221. /// <param name="bufferSize">Size of the buffer to be used.</param>
  222. /// <param name="closeSelf">Close the source stream <paramref name="self"/> after copying.</param>
  223. /// <param name="closeTarget">Close the <paramref name="target"/> stream after copying.</param>
  224. public static void CopyTo<S>(this S self, S target, int bufferSize, bool closeSelf, bool closeTarget) where S : Stream {
  225. try {
  226. try {
  227. int bytes = 0;
  228. byte[] buffer = new byte[bufferSize];
  229. do {
  230. bytes = self.Read(
  231. buffer, 0, bufferSize
  232. );
  233. if (bytes > 0) {
  234. target.Write(buffer, 0, bytes);
  235. target.Flush();
  236. }
  237. } while (bytes > 0);
  238. } finally {
  239. if (closeSelf) self.Close();
  240. }
  241. } finally {
  242. if (closeTarget) target.Close();
  243. }
  244. }
  245. /// <summary>
  246. /// Closes the given stream <paramref name="self"/> without throwing any exceptions.
  247. /// </summary>
  248. /// <param name="self">Stream instance to be closed.</param>
  249. public static void CloseQuietly(this Stream self) {
  250. try {
  251. self.Close();
  252. } catch (Exception) {
  253. ;
  254. }
  255. }
  256. #endregion
  257. #region Readers
  258. /// <summary>
  259. /// Closes the given text reader <paramref name="self"/> without throwing any exceptions.
  260. /// </summary>
  261. /// <param name="self">TextReader instance to be closed.</param>
  262. public static void CloseQuietly(this TextReader self) {
  263. try {
  264. self.Close();
  265. } catch (Exception) {
  266. ;
  267. }
  268. }
  269. #endregion
  270. }
  271. }