[Solved] Is there any way to shorten this code in C#? [closed]


Your code can be since just copy and pasted and that should never be your first thought of what to do, for example, this is all your doing to generate a string so you can just call this code in each of your sequences.

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);

Writing to the file is similar

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");

You should look up switch statements and figure out a way to get rid of the goto statements also.

2

solved Is there any way to shorten this code in C#? [closed]