有没有办法在C#中缩短这段代码?

时间:2014-07-08 06:06:33

标签: c# linq

我有一个作业,它告诉我创建一个文件,您可以在其中插入随机字母数字字符和关键字" VIRUS"进入文件。我认为我使用的逻辑足以完成这项任务。

我只是想知道有没有办法缩短我写的代码?因为我想更多地了解如何有效地编写代码。我还是一个菜鸟和自学成才;建设性反馈是值得欢迎的。这是我的任务。谢谢! :d

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RBC_Task_3 {
    class Program {
        static void Main(string[] args) {
            beginning: Console.WriteLine(
                "This program inputs a random alphanumeric array into a file.\n" +
                "The keyword \"VIRUS\" is sometimes inserted randomly inside the file.\n"
            );
            Console.WriteLine("Press any key to continue...");
            string folderName = @"c:\Top Folder";
            string path1 = Path.Combine(folderName, "File Folder");
            Directory.CreateDirectory(path1);
            if (Directory.Exists(path1)) {
                for (int i = 1; i <= 5; i++) {
                    string fileName = "file" + i + ".dat";
                    string filePath = Path.Combine(path1, fileName);
                    File.Create(filePath).Dispose();
                }
            }
            Console.ReadKey();
            Console.Clear();
            Console.Write("Press Y/y if you want to begin  ");
            string c = Console.ReadLine();
            Console.Clear();
            var rC = new Random();
            int sP = 0;
            if (c == "Y" || c == "y") {
                sP = rC.Next(1, 4);
                if (sP == 1) {
                    goto sequenceOne;
                } else if (sP == 2) {
                    goto sequenceTwo;
                } else {
                    goto sequenceThree;
                }
            } else {
                Console.WriteLine(
                    "Press Y/y if you want to begin.\nPress any key to continue"
                );
                Console.ReadKey();
                Console.Clear();
                goto beginning;
            }
            sequenceOne: var stringChars = new char[26];
            var random = new Random();
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            for (int i = 0; i < stringChars.Length; i++) {
                stringChars[i] = chars[random.Next(chars.Length)];
            }
            string string1 = new string(stringChars);
            File.WriteAllText(@"C:\Top Folder\File Folder\file1.dat",
                string1);
            using(StreamReader sr = File.OpenText(@
                "C:\Top Folder\File Folder\file1.dat")) {
                string s = "";
                while ((s = sr.ReadLine()) != null) {
                    Console.WriteLine(s);
                    Console.WriteLine("file1.dat is a clean file");
                    Console.WriteLine("Path to file1.dat - {0}", path1);
                }
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                goto end;
            }
            sequenceTwo: var stringChars2 = new char[26];
            var random2 = new Random();
            var chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZxxxxx";
            for (int i = 0; i < stringChars2.Length; i++) {
                stringChars2[i] = chars2[random2.Next(chars2.Length)];
            }
            string string2 = new string(stringChars2);
            string2 = string2.Replace("x", "\"VIRUS\"");
            File.WriteAllText(@"C:\Top Folder\File Folder\file2.dat",
                string2);
            using(StreamReader sr = File.OpenText(@
                "C:\Top Folder\FIle Folder\file2.dat")) {
                string s = "";
                while ((s = sr.ReadLine()) != null) {
                    Console.WriteLine(s);
                    Console.WriteLine(
                        "file2.dat is a HIGH THREAT virus file");
                    Console.WriteLine("Path to file2.dat - {0}\n",
                        path1);
                }
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                goto end;
            }
            sequenceThree: var stringChars3 = new char[26];
            var random3 = new Random();
            var chars3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZx";
            for (int i = 0; i < stringChars3.Length; i++) {
                stringChars3[i] = chars3[random3.Next(chars3.Length)];
            }
            string string3 = new string(stringChars3);
            string3 = string3.Replace("x", "\"VIRUS\"");
            File.WriteAllText(@"C:\Top Folder\File Folder\file3.dat",
                string3);
            using(StreamReader sr = File.OpenText(@
                "C:\Top Folder\File Folder\file3.dat")) {
                string s = "";
                while ((s = sr.ReadLine()) != null) {
                    Console.WriteLine(s);
                    Console.WriteLine(
                        "file3.dat is a MODERATE THREAT virus file"
                    );
                    Console.WriteLine("Path to file3.dat - {0}\n",
                        path1);
                }
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                goto end;
            }
            end: Console.WriteLine("\nDo you want to try again?Y/N");
            string end = Console.ReadLine();
            if (end == "Y" || end == "y") {
                Console.Clear();
                goto beginning;
            } else {
                Console.Clear();
                Console.WriteLine("Goodbye...Press any key to exit");
                Console.ReadKey();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的代码可以自复制和粘贴之后就应该永远是您第一次想到要做的事情,例如,这就是您生成字符串的所有操作,因此您可以调用此代码每个序列中的代码。

private string GenerateString(int idx)
{
    var stringChars = new char[26];
    var random = new Random();
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (int i = 0; i < stringChars.Length; i++) {
        stringChars[i] = chars[random.Next(chars.Length)];
    }
    return new string(stringChars);
}
//Example call (for sequence one) = string1 = GenerateString(1);

写入文件类似

private void WriteFile(int idx, string inputString ,string threatLevel)
{
    File.WriteAllText(@"C:\Top Folder\File Folder\file2.dat", inputString);
    string filePath = Path.Combine(@"C:\Top Folder\FIle Folder", 
                                     string.Format("file{0}.dat", idx));
    using(StreamReader sr = File.OpenText(filePath))
    {
        string s = "";
        while ((s = sr.ReadLine()) != null) {
            Console.WriteLine(s);
            Console.WriteLine("file{0}.dat is a {1} file", idx, threatLevel);
            Console.WriteLine("Path to file{0}.dat - {1}\n", idx, filePath);
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}
//WriteToFile(1, string1, "clean");
//WriteToFile(2, string2, "HIGH THREAT virus");
//WriteToFile(3, string2, "MODERATE THREAT virus");

你应该查找switch语句并找出摆脱goto语句的方法。