Ceasar Shift并写入文件

时间:2015-12-11 16:36:11

标签: c# c#-4.0

我正在尝试写入一个新文件(创建一个新文件),并且我想要在程序运行时显示在命令控制台中的所有内容(26个班次)都显示在新文件中。但是,当我使用file.WriteAllText()时,它会覆盖每个班次,然后只显示我创建的新文件中的第26个班次。

using System; 
using System.IO;
namespace ceasarAssignment
{
    public class caesarShift
    {
        public static void Main()
        { 
            string file = @"text.txt", // Name of the file that is being read     from
            encrypted = File.ReadAllText(file), // Reading the file
            decrypted = " ";
            char character = '0';
            int shift = 0;

            encrypted = encrypted.ToUpper(); // Puts the string into uppercase

            char[] alph = new char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',     'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',     'X', 'Y', 'Z' };
            // The array above is the alphabet (26 characters)
            Console.WriteLine("Encrypted text: \n{0}", encrypted);
            //Shows the encrypted text before it is decrypted

            for (int i = 0; i < alph.Length; i++) //adds a counter so that this          for loop will repeat until it has happened 26 times     
            {
                decrypted = "";
                foreach (char c in encrypted) 
                {
                    character = c;// each letter in the file is now defined as a     'character'

                  if (!char.IsLetter(c)) {
                        decrypted += c;
                        continue;
                    }
                    shift = Array.IndexOf(alph, character) - i; //searchs the     array for the character then minuses the counter to add the correct shift 
                    if (shift <= 0)
                        shift = shift + 26;// if the character is at the     beginning of the array go to the end

                    if (shift >= 26)
                        shift = shift - 26;// if the character is at the end of     the array go to the beginning


                    decrypted += alph[shift];
                }
                Console.WriteLine("\n Shift {0} \n {1}", i+1, decrypted); //Shows     the decrypted code for each 26 shifts
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使用File.AppendAllText(path, appendText)

每次循环运行时,

File.WriteAllText()都会覆盖该文件