Lean  $LEAN_TAG$
LazyStreamWriter.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 using System.IO;
16 
17 namespace QuantConnect.ToolBox
18 {
19  /// <summary>
20  /// This class wraps a <see cref="StreamWriter"/> so that the StreamWriter is only
21  /// instantiated until WriteLine() is called. This ensures that the file the StreamWriter is
22  /// writing to is only created if something is written to it. A StreamWriter will create a empty file
23  /// as soon as it is instantiated.
24  /// </summary>
25  public class LazyStreamWriter
26  {
27  private StreamWriter _streamWriter;
28  private readonly string _path;
29 
30  /// <summary>
31  /// Constructor for the <see cref="LazyStreamWriter"/>
32  /// </summary>
33  /// <param name="path">Path to the file that should be created</param>
34  public LazyStreamWriter(string path)
35  {
36  _path = path;
37  }
38 
39  /// <summary>
40  /// Wraps the WriteLine method of the StreamWriter.
41  /// </summary>
42  /// <param name="line">The line to write</param>
43  /// <remarks>Will instantiate the StreamWriter if this is the first time this method is called</remarks>
44  public void WriteLine(string line)
45  {
46  PrepareStreamWriter();
47 
48  _streamWriter.WriteLine(line);
49  }
50 
51  /// <summary>
52  /// Wraps the <see cref="StreamWriter.Flush()"/> method
53  /// </summary>
54  public void Flush()
55  {
56  if (_streamWriter != null)
57  {
58  _streamWriter.Flush();
59  }
60  }
61 
62  /// <summary>
63  /// Wraps the <see cref="StreamWriter.Close()"/> method
64  /// </summary>
65  public void Close()
66  {
67  if (_streamWriter != null)
68  {
69  _streamWriter.Close();
70  }
71  }
72 
73  /// <summary>
74  /// Checks if the StreamWriter is instantiated. If not, it will instantiate the StreamWriter
75  /// </summary>
76  private void PrepareStreamWriter()
77  {
78  if (_streamWriter == null)
79  {
80  _streamWriter = new StreamWriter(_path);
81  }
82  }
83  }
84 }