I used the example on here, but with little changes in order to write a base64 encoder method. I have a few points about the code:
I would like to use
using
statement, but I do not want to use inner "using" statements, so I use multiple variable declaration in a single "using" statement. Is that suitable in order to benefit from "using" statement for more than one object. Moreover, what are alternatives?Inside the
using
statement block, I used different try-catch blocks for each operation that can be throw an exception. I did not catch specific exceptions first an just use Exception class, but my goal is just return true or false which indicates the success status of the method. Is it a good practice to use different try-catch blocks and use "return" statement inside these blocks for resource handling?Also, I would like to use an extra try-catch block which surrounds the
using
blocks for the classes which haveDispose()
methods that can throw exceptions also. This is also discussed here. Is that a common approach, or should I completely stop usingusing
statements, for these cases.
public static bool ConvertToBase64(string inputFile, string outputFile)
{
try
{
using (FileStream inputFileStream = new FileStream(inputFile, FileMode.Open),
outputFileStream = new FileStream(outputFile, FileMode.Create))
{
try
{
ToBase64Transform base64Transform = new ToBase64Transform();
//Buffers for read/write operations
Byte[] outputBuffer = new byte[base64Transform.OutputBlockSize];
Byte[] inputBuffer = new byte[inputFileStream.Length];
//Offset to count the number of bytes transformed so far
int inputOffset = 0;
try
{
inputFileStream.Read(inputBuffer, 0, (int)inputFileStream.Length);
}
catch(Exception ex)
{
return false;
}
if (false == base64Transform.CanTransformMultipleBlocks)
{
while (inputBuffer.Length - inputOffset > base64Transform.InputBlockSize)
{
//Transform a block of input data
base64Transform.TransformBlock(inputBuffer, inputOffset, inputBuffer.Length - inputOffset, outputBuffer, 0);
inputOffset += base64Transform.InputBlockSize;
try
{
outputFileStream.Write(outputBuffer, 0, base64Transform.OutputBlockSize);
}
catch(Exception ex)
{
return false;
}
//Insert a new line after 76 characters
if (inputOffset % 19 == 0)
{
byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
outputFileStream.Write(newline, 0, newline.Length);
}
}
}
//Final block transform
try
{
byte[] lastBlock = base64Transform.TransformFinalBlock(inputBuffer, inputOffset, inputBuffer.Length - inputOffset);
outputFileStream.Write(lastBlock, 0, base64Transform.OutputBlockSize);
}
catch(Exception ex)
{
return false;
}
if (false == base64Transform.CanReuseTransform)
{
base64Transform.Clear();
}
}
catch(Exception ex)
{
return false;
}
}
}
catch(Exception ex)
{
return false;
}
return true;
}
try/catch
constructs are pointless since the outer one will already do exactly the same thing. \$\endgroup\$