protected void Open(StreamDirectionType streamDirection) { StreamDirection = streamDirection; // Open a stream for reading or writing FileStream fileStream = null; try { switch (StreamDirection) { case StreamDirectionType.Read: fileStream = File.Open(FilePath, FileMode.Open); _binaryReader = new BinaryReader(fileStream); break; case StreamDirectionType.Write: fileStream = File.Open(FilePath, FileMode.Open); _binaryWriter = new BinaryWriter(fileStream); break; default: throw new NotImplementedException("Case not implemented in switch statement."); } } catch (Exception) { // Close streams if (_binaryReader != null) { _binaryReader.Close(); _binaryReader = null; } if (_binaryWriter != null) { _binaryWriter.Close(); _binaryWriter = null; } // Close underlying stream if not already closed fileStream?.Close(); throw; } }
public void Open(string filePath, StreamDirectionType streamDirection) { FileStream fileStream = null; StreamDirection = streamDirection; // Open a stream for reading or writing try { switch (StreamDirection) { case StreamDirectionType.Read: fileStream = File.Open(filePath, FileMode.Open); StreamReader = new StreamReader(fileStream, Encoding.Default, false); break; case StreamDirectionType.Write: fileStream = File.Open(filePath, FileMode.Open); StreamWriter = new StreamWriter(fileStream, Encoding.Default); break; default: throw new NotImplementedException("Case not implemented in switch statement."); } } catch (Exception) { // Close streams if (StreamReader != null) { StreamReader.Close(); StreamReader = null; } if (StreamWriter != null) { StreamWriter.Close(); StreamWriter = null; } // Close underlying stream fileStream?.Close(); throw; } }