我的程序(多项选择考试)出现问题,我不知道如何读取多个文件中所有文本的代码。
应试者首先注册他们的(姓名,年龄,性别,联系电话),然后进行考试。
考试后将显示结果(正确答案,错误答案,总项目数)。
之后,所有这些都将使用StreamWriter
保存到.txt文件中
注意:我的流媒体编写器具有自动命名功能(例如Windows)
例如:
xReg.txt, xReg(1).txt, xReg(2), xReg(n).txt
这就是我所做的,它只写了所有.txt文件的所有内容,但我希望可以选择在菜单中查看1个文件。
public class FilesL
{
public static void alltxt()
{
Console.Clear();
foreach (var file in Directory.GetFiles("C:\\Examinees", "*.txt",
SearchOption.AllDirectories))
{
var a = File.ReadAllText(file);
Console.WriteLine(a);
}
Console.WriteLine();
Console.ReadKey();
Ad.Admin();
}
}
这是我的管理员登录菜单btw
public class Ad
{
private static string User = "";
private static string Password = "";
private static int instance = 3;
public static string fileName = @"C:\\Examinees\xReg.txt";
private static void V()
{
Console.WriteLine("\n\t\tAdministrator");
Console.WriteLine("\n\nMenu\n");
Console.WriteLine("\t1) View Examinees' Results\n");
Console.WriteLine("\t2) Restart Program\n");
Console.WriteLine("\t3) View Test\n");
Console.WriteLine("\t4) Terminate Program\n\n");
Console.Write("Select: ");
int choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
FilesL.alltxt();
break;
case 2:
Home.H();
break;
case 3:
Questions.exam();
break;
case 4:
Clear.terminate();
break;
default:
Console.WriteLine("Invalid choice, please try again!");
Console.ReadKey();
V();
break;
}
}
public static void Admin()
{
Console.Clear();
do
{
Console.WriteLine("\nYou need to log-in to confirm that you are the ADMINISTRATOR.");
Console.WriteLine("\n\t╔═════════════════════════════════════════╗");
Console.WriteLine("\t║\t ! Login Confirmation ! ║");
Console.WriteLine("\t╚═════════════════════════════════════════╝");
Console.Write("\n\tEnter Your Username: ");
User = Console.ReadLine();
Console.Write("\tEnter Your Password: ");
Password = Console.ReadLine();
if (User == "Admin" && Password == "AAAA")
{
Console.Clear();
V();
}
else
{
instance--;
Console.WriteLine("\nSorry, you entered a wrong input! \nPress
Enter to Continue.\n\nAttempts Left: {0}", instance);
Console.ReadKey();
Console.Clear();
if (instance == 0)
{
Clear.terminate();
}
}
}
while (User != "Admin" || Password != "AAAA");
Console.Clear();
}}
答案 0 :(得分:0)
string[] files = Directory.GetFiles(@"D:\test\", "*.txt");
List<string> data = new List<string>();
foreach (string file in files)
{
using (StreamReader sr = File.OpenText(file))
{
string fileContent = sr.ReadToEnd();
data.Add(fileContent);
}
}
答案 1 :(得分:-1)
请找到其他解决方案
using System.IO;
static void Main(string[] args)
{
var txtFiles = Directory.EnumerateFiles(@"D:\SampleStackoverflow\", "*.txt");
foreach (string currentFile in txtFiles)
{
var fileStream = new FileStream(currentFile, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
//Do the action of Storing the file content
}
}
}
}