Exercise
File encrypter
Objetive
Create a program to encrypt a text file into another text file.
Example Code
// Import the System namespace for basic functionality
using System;
// Import the IO namespace for file handling
using System.IO;
// Encrypt class to handle the encryption logic
class Encrypter
{
// Method to encrypt the content of the input file and save to the output file
public static void EncryptFile(string inputFilePath, string outputFilePath, string key)
{
// Read the content of the input file
string content = File.ReadAllText(inputFilePath);
// Encrypt the content using the key
string encryptedContent = EncryptContent(content, key);
// Write the encrypted content to the output file
File.WriteAllText(outputFilePath, encryptedContent);
}
// Method to encrypt the content of the file using a simple Caesar cipher
private static string EncryptContent(string content, string key)
{
// Convert the key to a number (for simplicity, just use the length of the key)
int keyLength = key.Length;
// Create a character array to store the encrypted content
char[] encryptedChars = new char[content.Length];
// Loop through each character in the content
for (int i = 0; i < content.Length; i++)
{
// Get the current character
char currentChar = content[i];
// Encrypt the character using the Caesar cipher (shift by keyLength)
char encryptedChar = (char)(currentChar + keyLength);
// Store the encrypted character
encryptedChars[i] = encryptedChar;
}
// Convert the encrypted character array back to a string
return new string(encryptedChars);
}
}
class FileEncrypter
{
static void Main(string[] args)
{
// Ask the user for the input file path
Console.WriteLine("Enter the path of the file to encrypt:");
// Get the input file path from the user
string inputFilePath = Console.ReadLine();
// Ask the user for the output file path
Console.WriteLine("Enter the output file path to save the encrypted file:");
// Get the output file path from the user
string outputFilePath = Console.ReadLine();
// Ask the user for the encryption key (simple string-based key)
Console.WriteLine("Enter the encryption key (any string):");
// Get the key from the user
string key = Console.ReadLine();
// Start of try block to handle any file or encryption errors
try
{
// Use the Encrypter class to encrypt the input file and save to the output file
Encrypter.EncryptFile(inputFilePath, outputFilePath, key);
// Inform the user that the encryption process is complete
Console.WriteLine("File has been successfully encrypted and saved as: " + outputFilePath);
}
catch (Exception ex) // Catch any exceptions that may occur during the process
{
// Print the exception message if an error occurs
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}