Exercise
File encrypter
Objetive
Create a program to encrypt a text file into another text file.
Example Code
using System;
using System.IO;
class Encrypter
{
public static void EncryptFile(string inputFilePath, string outputFilePath, string key)
{
string content = File.ReadAllText(inputFilePath);
string encryptedContent = EncryptContent(content, key);
File.WriteAllText(outputFilePath, encryptedContent);
}
private static string EncryptContent(string content, string key)
{
int keyLength = key.Length;
char[] encryptedChars = new char[content.Length];
for (int i = 0; i < content.Length; i++)
{
char currentChar = content[i];
char encryptedChar = (char)(currentChar + keyLength);
encryptedChars[i] = encryptedChar;
}
return new string(encryptedChars);
}
}
class FileEncrypter
{
static void Main(string[] args)
{
Console.WriteLine("Enter the path of the file to encrypt:");
string inputFilePath = Console.ReadLine();
Console.WriteLine("Enter the output file path to save the encrypted file:");
string outputFilePath = Console.ReadLine();
Console.WriteLine("Enter the encryption key (any string):");
string key = Console.ReadLine();
try
{
Encrypter.EncryptFile(inputFilePath, outputFilePath, key);
Console.WriteLine("File has been successfully encrypted and saved as: " + outputFilePath);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}