/// <summary> /// Converts a byte array to a base64 string one block at a time. /// </summary> /// <param name="data">The data.</param> /// <returns></returns> public static string ToBase64(byte[] data) { StringBuilder builder = new StringBuilder(); using (StringWriter writer = new StringWriter(builder)) { using (ToBase64Transform transformation = new ToBase64Transform()) { // Transform the data in chunks the size of InputBlockSize. byte[] bufferedOutputBytes = new byte[transformation.OutputBlockSize]; int i = 0; int inputBlockSize = transformation.InputBlockSize; while (data.Length - i > inputBlockSize) { transformation.TransformBlock(data, i, data.Length - i, bufferedOutputBytes, 0); i += inputBlockSize; writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes)); } // Transform the final block of data. bufferedOutputBytes = transformation.TransformFinalBlock(data, i, data.Length - i); writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes)); // Free up any used resources. transformation.Clear(); } writer.Close(); } return(builder.ToString()); }
public static string Encode(byte[] data) { var builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { using (var transformation = new ToBase64Transform()) { var bufferedOutputBytes = new byte[transformation.OutputBlockSize]; int i = 0; int inputBlockSize = transformation.InputBlockSize; while (data.Length - i > inputBlockSize) { transformation.TransformBlock(data, i, data.Length - i, bufferedOutputBytes, 0); i += inputBlockSize; writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes, 0, bufferedOutputBytes.Length)); } bufferedOutputBytes = transformation.TransformFinalBlock(data, i, data.Length - i); writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes, 0, bufferedOutputBytes.Length)); transformation.Clear(); } writer.Close(); } return(builder.ToString()); }
public void TransformFinalBlock_Dispose() { byte[] input = new byte [3]; ToBase64Transform t = new ToBase64Transform(); t.Clear(); t.TransformFinalBlock(input, 0, input.Length); }
public void TransformBlock_Dispose() { byte[] input = new byte [3]; byte[] output = new byte [4]; ToBase64Transform t = new ToBase64Transform(); t.Clear(); t.TransformBlock(input, 0, input.Length, output, 0); }
/// <summary> /// Transforms string to byte array /// </summary> /// <param name="str"></param> /// <returns></returns> public static byte[] Transform(string str) { // Create a new ToBase64Transform object to convert to base 64. ToBase64Transform base64Transform = new ToBase64Transform(); // Create a new byte array with the size of the output block size. byte[] outputBytes = new byte[base64Transform.OutputBlockSize]; // Retrieve the file contents into a byte array. byte[] inputBytes = HexStringToByteArray(str); // Verify that multiple blocks can not be transformed. if (!base64Transform.CanTransformMultipleBlocks) { // Initializie the offset size. int inputOffset = 0; // Iterate through inputBytes transforming by blockSize. int inputBlockSize = base64Transform.InputBlockSize; while (inputBytes.Length - inputOffset > inputBlockSize) { base64Transform.TransformBlock( inputBytes, inputOffset, inputBytes.Length - inputOffset, outputBytes, 0); inputOffset += base64Transform.InputBlockSize; } // Transform the final block of data. outputBytes = base64Transform.TransformFinalBlock( inputBytes, inputOffset, inputBytes.Length - inputOffset); //Determine if the current transform can be reused. if (!base64Transform.CanReuseTransform) { // Free up any used resources. base64Transform.Clear(); } } return(outputBytes); }
/// <summary> /// Converts a byte array to a base64 string one block at a time. /// </summary> /// <param name="data">The data.</param> /// <returns></returns> public static string ToBase64(byte[] data) { #if WINDOWS_PHONE || NETFX_CORE return(Convert.ToBase64String(data)); #else var builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { using (var transformation = new ToBase64Transform()) { // Transform the data in chunks the size of InputBlockSize. var bufferedOutputBytes = new byte[transformation.OutputBlockSize]; int i = 0; int inputBlockSize = transformation.InputBlockSize; while (data.Length - i > inputBlockSize) { transformation.TransformBlock(data, i, data.Length - i, bufferedOutputBytes, 0); i += inputBlockSize; writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes, 0, bufferedOutputBytes.Length)); } // Transform the final block of data. bufferedOutputBytes = transformation.TransformFinalBlock(data, i, data.Length - i); writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes, 0, bufferedOutputBytes.Length)); // Free up any used resources. transformation.Clear(); } writer.Close(); } return(builder.ToString()); #endif }
// Read in the specified source file and write out an encoded target file. private static void EncodeFromFile(string sourceFile, string targetFile) { // Verify members.cs exists at the specified directory. if (!File.Exists(sourceFile)) { Console.Write("Unable to locate source file located at "); Console.WriteLine(sourceFile + "."); Console.Write("Please correct the path and run the "); Console.WriteLine("sample again."); return; } // Retrieve the input and output file streams. using (FileStream inputFileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read)) { using (FileStream outputFileStream = new FileStream(targetFile, FileMode.Create, FileAccess.Write)) { // Create a new ToBase64Transform object to convert to base 64. ToBase64Transform base64Transform = new ToBase64Transform(); // Create a new byte array with the size of the output block size. byte[] outputBytes = new byte[base64Transform.OutputBlockSize]; // Retrieve the file contents into a byte array. byte[] inputBytes = new byte[inputFileStream.Length]; inputFileStream.Read(inputBytes, 0, inputBytes.Length); // Verify that multiple blocks can not be transformed. if (!base64Transform.CanTransformMultipleBlocks) { // Initializie the offset size. int inputOffset = 0; // Iterate through inputBytes transforming by blockSize. int inputBlockSize = base64Transform.InputBlockSize; while (inputBytes.Length - inputOffset > inputBlockSize) { base64Transform.TransformBlock( inputBytes, inputOffset, inputBytes.Length - inputOffset, outputBytes, 0); inputOffset += base64Transform.InputBlockSize; outputFileStream.Write( outputBytes, 0, base64Transform.OutputBlockSize); } // Transform the final block of data. outputBytes = base64Transform.TransformFinalBlock( inputBytes, inputOffset, inputBytes.Length - inputOffset); outputFileStream.Write(outputBytes, 0, outputBytes.Length); Console.WriteLine("Created encoded file at " + targetFile); } // Determine if the current transform can be reused. if (!base64Transform.CanReuseTransform) { // Free up any used resources. base64Transform.Clear(); } } } }
//methods /// <summary> /// Converts file to base64 encoding. /// </summary> /// <param name="srcFile">File containing data to be encoded.</param> /// <param name="targetFile">Output file that will contain the base64 encoded data.</param> /// <param name="st">A StatusTimer object to use for timing the encode operation.</param> public void EncodeFileToBase64(string srcFile, string targetFile, StatusTimer st) { byte[] bytes = new byte[BufferSize]; FileStream fs = null; StreamWriter sw = null; FileStream fsOut = null; int bytesRead = 0; long totalBytesRead = 0; bool errorOccurred = false; // Open srcFile in read-only mode. try { if (st == null) { throw new ArgumentNullException("StatusTime must be specified for this routine."); } st.NumSecondsInterval = _statusReportIntervalSeconds; fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize); long sourceSize = new FileInfo(srcFile).Length; if (sourceSize <= BufferSize) { // Open stream writer sw = new StreamWriter(targetFile, false, Encoding.ASCII); bytesRead = fs.Read(bytes, 0, BufferSize); if (bytesRead > 0) { if (currentStatusReport != null) { if (st.StatusReportDue()) { currentStatusReport("EncodeToBase64", "In Progress", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime()); } } string base64String = Convert.ToBase64String(bytes, 0, bytesRead); totalBytesRead += bytesRead; sw.Write(base64String); if (currentStatusReport != null) { if (st.StatusReportDue()) { currentStatusReport("EncodeToBase64", "Completed", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime()); } } } } else { // Instantiate a ToBase64Transform object. ToBase64Transform transf = new ToBase64Transform(); // Arrays to hold input and output bytes. byte[] inputBytes = new byte[transf.InputBlockSize]; byte[] outputBytes = new byte[transf.OutputBlockSize]; int bytesWritten; fsOut = new FileStream(targetFile, FileMode.Create, FileAccess.Write); do { if (currentStatusReport != null) { if (st.StatusReportDue()) { currentStatusReport("EncodeToBase64", "In Progress", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime()); } } bytesRead = fs.Read(inputBytes, 0, inputBytes.Length); totalBytesRead += bytesRead; bytesWritten = transf.TransformBlock(inputBytes, 0, bytesRead, outputBytes, 0); fsOut.Write(outputBytes, 0, bytesWritten); } while (sourceSize - totalBytesRead > transf.InputBlockSize); // Transform the final block of data. bytesRead = fs.Read(inputBytes, 0, inputBytes.Length); totalBytesRead += bytesRead; byte[] finalOutputBytes = transf.TransformFinalBlock(inputBytes, 0, bytesRead); fsOut.Write(finalOutputBytes, 0, finalOutputBytes.Length); if (currentStatusReport != null) { currentStatusReport("EncodeToBase64", "Completed", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime()); } // Clear Base64Transform object. transf.Clear(); } } catch (IOException ex) { errorOccurred = true; _msg.Length = 0; _msg.Append(AppMessages.FormatErrorMessage(ex)); throw new IOException(_msg.ToString()); } catch (SecurityException ex) { errorOccurred = true; _msg.Length = 0; _msg.Append(AppMessages.FormatErrorMessage(ex)); throw new SecurityException(_msg.ToString()); } catch (UnauthorizedAccessException ex) { errorOccurred = true; _msg.Length = 0; _msg.Append(AppMessages.FormatErrorMessage(ex)); throw new UnauthorizedAccessException(_msg.ToString()); } finally { if (errorOccurred) { if (currentStatusReport != null) { currentStatusReport("EncodeToBase64", "ErrorCancel", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime()); } } if (sw != null) { sw.Close(); } if (fs != null) { fs.Dispose(); fs.Close(); } if (fsOut != null) { fsOut.Dispose(); fsOut.Close(); } } }
//properties //methods /// <summary> /// Converts file to base64 encoding. /// </summary> /// <param name="srcFile">File containing data to be encoded.</param> /// <param name="targetFile">Output file that will contain the base64 encoded data.</param> public void EncodeFileToBase64(string srcFile, string targetFile) { byte[] bytes = new byte[BufferSize]; FileStream fs = null; StreamWriter sw = null; FileStream fsOut = null; //int bytesRead = 0; //int totalBytesRead = 0; int bytesRead = 0; long totalBytesRead = 0; // Open srcFile in read-only mode. try { fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize); long sourceSize = new FileInfo(srcFile).Length; if (sourceSize <= BufferSize) { // Open stream writer sw = new StreamWriter(targetFile, false, Encoding.ASCII); bytesRead = fs.Read(bytes, 0, BufferSize); if (bytesRead > 0) { string base64String = Convert.ToBase64String(bytes, 0, bytesRead); totalBytesRead += bytesRead; sw.Write(base64String); } } else { // Instantiate a ToBase64Transform object. ToBase64Transform transf = new ToBase64Transform(); // Arrays to hold input and output bytes. byte[] inputBytes = new byte[transf.InputBlockSize]; byte[] outputBytes = new byte[transf.OutputBlockSize]; int bytesWritten; fsOut = new FileStream(targetFile, FileMode.Create, FileAccess.Write); do { bytesRead = fs.Read(inputBytes, 0, inputBytes.Length); totalBytesRead += bytesRead; bytesWritten = transf.TransformBlock(inputBytes, 0, bytesRead, outputBytes, 0); fsOut.Write(outputBytes, 0, bytesWritten); } while (sourceSize - totalBytesRead > transf.InputBlockSize); // Transform the final block of data. bytesRead = fs.Read(inputBytes, 0, inputBytes.Length); byte[] finalOutputBytes = transf.TransformFinalBlock(inputBytes, 0, bytesRead); fsOut.Write(finalOutputBytes, 0, finalOutputBytes.Length); // Clear Base64Transform object. transf.Clear(); } } catch (IOException ex) { _msg.Length = 0; _msg.Append(AppMessages.FormatErrorMessage(ex)); throw new IOException(_msg.ToString()); } catch (SecurityException ex) { _msg.Length = 0; _msg.Append(AppMessages.FormatErrorMessage(ex)); throw new SecurityException(_msg.ToString()); } catch (UnauthorizedAccessException ex) { _msg.Length = 0; _msg.Append(AppMessages.FormatErrorMessage(ex)); throw new UnauthorizedAccessException(_msg.ToString()); } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Dispose(); fs.Close(); } if (fsOut != null) { fsOut.Dispose(); fsOut.Close(); } } }
private static void EncodeFile(string srcFile, string targetFile) { byte[] bytes = new byte[BufferSize]; FileStream fs = null; StreamWriter sw = null; FileStream fsOut = null; int bytesRead = 0; int totalBytesRead = 0; // Open srcFile in read-only mode. try { fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize); long sourceSize = new FileInfo(srcFile).Length; if (sourceSize <= BufferSize) { // Open stream writer sw = new StreamWriter(targetFile, false, Encoding.ASCII); bytesRead = fs.Read(bytes, 0, BufferSize); if (bytesRead > 0) { string base64String = Convert.ToBase64String(bytes, 0, bytesRead); totalBytesRead += bytesRead; Console.CursorLeft = 0; Console.Write(rm.GetString("ProgressEncodedMsg"), totalBytesRead); sw.Write(base64String); } } else { // Instantiate a ToBase64Transform object. ToBase64Transform transf = new ToBase64Transform(); // Arrays to hold input and output bytes. byte[] inputBytes = new byte[transf.InputBlockSize]; byte[] outputBytes = new byte[transf.OutputBlockSize]; int bytesWritten; fsOut = new FileStream(targetFile, FileMode.Create, FileAccess.Write); do { bytesRead = fs.Read(inputBytes, 0, inputBytes.Length); totalBytesRead += bytesRead; bytesWritten = transf.TransformBlock(inputBytes, 0, bytesRead, outputBytes, 0); fsOut.Write(outputBytes, 0, bytesWritten); } while (sourceSize - totalBytesRead > transf.InputBlockSize); // Transform the final block of data. bytesRead = fs.Read(inputBytes, 0, inputBytes.Length); byte[] finalOutputBytes = transf.TransformFinalBlock(inputBytes, 0, bytesRead); fsOut.Write(finalOutputBytes, 0, finalOutputBytes.Length); // Clear Base64Transform object. transf.Clear(); } Console.WriteLine(); Console.WriteLine(rm.GetString("SuccessEncodedMsg"), srcFile, targetFile); } catch (IOException) { Console.WriteLine(rm.GetString("IOException")); return; } catch (SecurityException) { Console.WriteLine(rm.GetString("SecurityException"), srcFile); return; } catch (UnauthorizedAccessException) { Console.WriteLine(rm.GetString("AccessException"), srcFile); return; } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Dispose(); fs.Close(); } if (fsOut != null) { fsOut.Dispose(); fsOut.Close(); } } }