Lean  $LEAN_TAG$
FileHandler.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System.IO;
17 using System.Collections.Generic;
18 
20 {
21  /// <summary>
22  /// Raw file handler
23  /// </summary>
24  /// <remarks>Useful to abstract file operations for <see cref="LocalObjectStore"/></remarks>
25  public class FileHandler
26  {
27  /// <summary>
28  /// True if the given file path exists
29  /// </summary>
30  public virtual bool Exists(string path)
31  {
32  return File.Exists(path);
33  }
34 
35  /// <summary>
36  /// Will delete the given file path
37  /// </summary>
38  public virtual void Delete(string path)
39  {
40  File.Delete(path);
41  }
42 
43  /// <summary>
44  /// Will write the given byte array at the target file path
45  /// </summary>
46  public virtual void WriteAllBytes(string path, byte[] data)
47  {
48  File.WriteAllBytes(path, data);
49  }
50 
51  /// <summary>
52  /// Read all bytes in the given file path
53  /// </summary>
54  public virtual byte[] ReadAllBytes(string path)
55  {
56  return File.ReadAllBytes(path);
57  }
58 
59  /// <summary>
60  /// Will try to fetch the given file length, will return 0 if it doesn't exist
61  /// </summary>
62  public virtual long TryGetFileLength(string path)
63  {
64  var fileInfo = new FileInfo(path);
65  if (fileInfo.Exists)
66  {
67  return fileInfo.Length;
68  }
69  return 0;
70  }
71 
72  /// <summary>
73  /// True if the given directory exists
74  /// </summary>
75  public virtual bool DirectoryExists(string path)
76  {
77  return Directory.Exists(path);
78  }
79 
80  /// <summary>
81  /// Create the requested directory path
82  /// </summary>
83  public virtual DirectoryInfo CreateDirectory(string path)
84  {
85  return Directory.CreateDirectory(path);
86  }
87 
88  /// <summary>
89  /// Enumerate the files in the target path
90  /// </summary>
91  public virtual IEnumerable<FileInfo> EnumerateFiles(string path, string pattern, SearchOption searchOption, out string rootfolder)
92  {
93  var directoryInfo = new DirectoryInfo(path);
94  rootfolder = directoryInfo.FullName;
95  return directoryInfo.EnumerateFiles(pattern, searchOption);
96  }
97  }
98 }