如何将输出保存到文本文件

时间:2015-11-26 12:45:39

标签: c#

我已经创建了一个程序,我可以解密一些加密文本,它通过读取文本文件并一次一个字母地移动文本来实现这一点,并且这样做了26次,但我可以'得到它保存并将输出写入文本文件,这是我的代码,如果可能的话,我将不胜感激,谢谢

using System;
using System.IO;

namespace Assignment1
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            //Writing to the screen
            Console.WriteLine("Welcome to the Ceaser Cipher Shift Program");
            Console.WriteLine("Would You Like to Decrypt a File (y for yes/n for no)");

            string userValue = Console.ReadLine();

            //User's value is set to userValue
            // if the user types "y", activate the decryption method
            if (userValue.ToLower() == "y")
            {
                decryption();
            }

            // if the user types in "n", write "Goodbye" and close the program
            if (userValue.ToLower() == "n")
            {
                Console.WriteLine("Goodbye");
                Console.ReadLine();
                Environment.Exit(0);
                //Environment.exit closes the program
            }
        }

        //Decryption method
        public static void decryption()
        {
            //ShiftLine is equal to new char
            char[] ShiftLine = new char[0];

            //If the shift is smaller or equal to 25, continue to shift one at a time
            for (int shift = 1; shift <= 26; shift++)
            {
                //This reads the encryptefd text file into the program
                string textFile = @"C:\Users\Anthony\Desktop\caesarShiftEncoded.txt";
                //The string "test" reads all the lines of the textFile
                string[] text = File.ReadAllLines(textFile);

                foreach (string line in text)
                {
                    //Sets currentLetter to 0
                    int CurrentLetter = 0;
                    int[] ShiftNumbers = new int[line.Length];
                    ShiftLine = new char[line.Length];

                    foreach (char letter in line)
                    {
                        ShiftNumbers[CurrentLetter] = ConvertLetterToNumber(letter);
                        ShiftNumbers[CurrentLetter] = ShiftCipher(ShiftNumbers[CurrentLetter], shift);
                        ShiftLine[CurrentLetter] = ConvertNumberToLetter(ShiftNumbers[CurrentLetter]);
                        CurrentLetter++;
                    }

                    Console.WriteLine(string.Join("", ShiftLine));
                }

                //Console.WriteLine (textFile.Length);
                Console.WriteLine("This is Shift No: {0}", shift);
            }

            Console.WriteLine("Which Shift Would You Like To Write to a Text File: ");
            string userNumber = Console.ReadLine();

            if (userNumber.ToLower() == "1 =< 26")
            {
                using (StreamWriter text = new StreamWriter("TextWrittenFile.txt"))
                {
                    foreach (char line in ShiftLine)
                    {
                       text.WriteLine(ShiftLine);
                       File.WriteAllText("C:\Users\Anthony\Desktop\DecryptedText.txt", ShiftLine);
                    }
                }
            }
        }

        public static int ShiftCipher(int Number, int Shift)
        {
            if (Number == 27)
            {
                return 27;
            }
            else if (Number == 28)
            {
                return 28;
            }
            else if (Number > Shift)
            {
                return (Number - Shift);
            }
            else if (Number <= Shift)
            {
                return (26 + (Number - Shift));
            }
            else
            {
                return 0;
            }
        }

        public static int ConvertLetterToNumber(char Letter)
        {
            switch (Char.ToLower(Letter))
            {
                case 'a':
                    return 1;
                case 'b':
                    return 2;
                case 'c':
                    return 3;
                case 'd':
                    return 4;
                case 'e':
                    return 5;
                case 'f':
                    return 6;
                case 'g':
                    return 7;
                case 'h':
                    return 8;
                case 'i':
                    return 9;
                case 'j':
                    return 10;
                case 'k':
                    return 11;
                case 'l':
                    return 12;
                case 'm':
                    return 13;
                case 'n':
                    return 14;
                case 'o':
                    return 15;
                case 'p':
                    return 16;
                case 'q':
                    return 17;
                case 'r':
                    return 18;
                case 's':
                    return 19;
                case 't':
                    return 20;
                case 'u':
                    return 21;
                case 'v':
                    return 22;
                case 'w':
                    return 23;
                case 'x':
                    return 24;
                case 'y':
                    return 25;
                case 'z':
                    return 26;
                case ' ':
                    return 27;
                default:
                    return 0;
            }
        }

        public static char ConvertNumberToLetter(int Number)
        {
            switch (Number)
            {
                case 1:
                    return 'a';
                case 2:
                    return 'b';
                case 3:
                    return 'c';
                case 4:
                    return 'd';
                case 5:
                    return 'e';
                case 6:
                    return 'f';
                case 7:
                    return 'g';
                case 8:
                    return 'h';
                case 9:
                    return 'i';
                case 10:
                    return 'j';
                case 11:
                    return 'k';
                case 12:
                    return 'l';
                case 13:
                    return 'm';
                case 14:
                    return 'n';
                case 15:
                    return 'o';
                case 16:
                    return 'p';
                case 17:
                    return 'q';
                case 18:
                    return 'r';
                case 19:
                    return 's';
                case 20:
                    return 't';
                case 21:
                    return 'u';
                case 22:
                    return 'v';
                case 23:
                    return 'w';
                case 24:
                    return 'x';
                case 25:
                    return 'y';
                case 26:
                    return 'z';
                case 27:
                    return ' ';
                default:
                    return '0';
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

由于您的ShiftLine似乎是一系列字符,因此可能很简单:

File.WriteAllText("C:\Users\Anthony\Desktop\DecryptedText.txt", new string(ShiftLine));

(而不是你的循环[btw:你的循环在任何回合中覆盖文件......])

答案 1 :(得分:1)

实际上有一些事情你可以改进。 如果用户只能按yn,则可以使用Console.ReadKey()方法,而不是让用户输入完整的文本行。通过使用重载方法并指定true作为参数,您甚至不会看到写入控制台窗口(Console.ReadKey(true))的按下键。

因此,您可以将当前if语句与switch (Console.ReadKey(true).Key)进行交换,并构建case ConsoleKey.Y:

等案例

所以Main方法看起来像这样:

public static void Main(string[] args)
{
    //Writing to the screen
    Console.WriteLine("Welcome to the Ceaser Cipher Shift Program");
    Console.WriteLine("Would You Like to Decrypt a File (y for yes/n for no)");

    switch (Console.ReadKey(true).Key)
    {
        // if the user types "y", activate the decryption method
        case ConsoleKey.Y:
            decryption();
            break;

        // if the user types in "n", write "Goodbye" and close the program
        case ConsoleKey.N:
        default:
            Console.WriteLine("Goodbye");
            Environment.Exit(0);
            break;
    }
}

我想您接下来要做的就是使用Caesar cipher来加密/解密数据。

因此,你只是&#34;需要改变每个角色,这比写switch - case语句要容易得多。这种加密背后的想法是,你接受一个字符并用另一个字符替换offset个字符。解密是另一回事。

因此,构建一个能够为指定文本完全执行此操作的方法会更容易。

您需要考虑两种特殊情况:如果您正在查看的值位于下边界并且您减去偏移量(意味着&#34;新&#34;值将低于零)会发生什么情况)。第二个代表上边界的相同情况。

可以使用if语句解决这些情况,也可以通过查看具有最大值范围的其余部分来更轻松地解决这些问题。 (text[i] + offset) % NumberOfPossibleCharacters应该做到这一点。

知道了这一点,你可以轻松地构建一个类似下面的方法(我假设,没有任何字符的值大于127):

static string Encrypt(string data, int offset)
{
    string result = string.Empty;

    for (int i = 0; i < data.Length; i++)
    {
        // Add the offset to the current character and just take the
        // rest of the division by 127. Afterwards cast it back to a character
        // (because it will be a number due to + and %)
        result += (char)((data[i] + offset) % 127);
    }

    return result;
}

请注意,像+=这样的字符串操作每次都会导致创建一个新字符串,因此从(内存)性能的角度来看,它不是一个很好的例子。有更好的方法来使用StringBuilder类。

我希望这提示你能更好地解决你的家庭作业; - )