在 C# 中创建将数据保存在 .txt 或 .csv 文件中以供操作/使用的控制台应用程序的问题

问题描述 投票:0回答:0

编辑:我解决了将数据添加到 .txt 文件的问题,但是现在当我运行控制台程序并添加新员工时,它会像计划的那样为每个员工提供随机 ID #,但显示的不是什么记录在 .txt 文件中。然后,当我按 ID 搜索 Employee 时,它不起作用,除非我正在查看文件本身而不是终端中显示的内容。有什么想法吗?

我的任务是创建一个简单的控制台程序,该程序将接受各种输入并将数据存储在列表中以及要保存的外部文件中。当我创建执行此类操作的方法时,调用要创建的文件和从用户输入中获得的数据不会将数据传输到 .txt 或 .csv 文件。我的代码按预期工作,除非您选择“按 ID 查找员工”和“姓名”查找选项。我愿意接受您看到的任何可能需要完成的更正,但我主要想知道为什么文件的 StreamWriter 不起作用。

EmployeeRoster.cs

public class Employee {
    public string name { get; set;}
    public int employeeID { get; set;}
    public string title { get; set;}
    public DateTime startDate { get; set;}
    
    public Employee() {
        this.name = "";
        this.employeeID = 0;
        this.title = "";
        this.startDate = DateTime.Now;
    }

    public Employee(string name, string title, DateTime startDate) {
        this.name = name;
        this.title = title;
        this.startDate = startDate;

        Random IDNum = new Random();
        this.employeeID = IDNum.Next(0000, 9999);
    }

    public virtual void printDetails(){

    Console.WriteLine("Employee details:");
    Console.WriteLine("ID: {0}", employeeID);
    Console.WriteLine("Name: {0}", name);
    Console.WriteLine("Title: {0}", title);
    Console.WriteLine("StartDate: {0}", startDate.ToString("yyyy-MM-dd"));
    }    

    private const string fileName = "EmployeeData.txt";

    public void CreateNewEmployee(string name, string title, DateTime startDate)
    {
        Employee employee = new Employee(name, title, startDate);
        string employeeData = $"{employee.employeeID},{employee.name},{employee.title},{employee.startDate.ToString("MM/dd/yyyy")}";
        using (StreamWriter writer = new StreamWriter(fileName, true))
        {
            writer.WriteLine(employeeData);
        }
        Console.WriteLine($"Employee {employee.name} with ID {employee.employeeID} has been created.");
    }

    
    public static void employeeIDSearch(int employeeID) {
        string[] employees = File.ReadAllLines(fileName);
        foreach (string employee in employees)
        {
            string[] employeeData = employee.Split(',');
            if (int.Parse(employeeData[0]) == employeeID)
            {
                Console.WriteLine($"ID: {employeeData[0]}, Name: {employeeData[1]}, Title: {employeeData[2]}, Start Date: {employeeData[3]}");
                return;
            }
        }
        Console.WriteLine($"No employee found with ID {employeeID}.");
    

    }

    public static void employeeNameSearch(string name)
    {
        string[] employees = File.ReadAllLines(fileName);
                foreach (string employee in employees)
                {
                    string[] employeeData = employee.Split(',');
                    if (employeeData[1].ToLower().Contains(name.ToLower()))
                    {
                        Console.WriteLine($"ID: {employeeData[0]}, Name: {employeeData[1]}, Title: {employeeData[2]}, Start Date: {employeeData[3]}");
                    }
                }
    }

    public static void deleteEmployeeByID(int employeeID)
    {
        string[] employees = File.ReadAllLines(fileName);
        List<string> updatedEmployees = new List<string>();
        bool employeeFound = false;
        foreach (string employee in employees) {
            
            string[] employeeData = employee.Split(',');

            if (int.Parse(employeeData[0]) != employeeID) {
                updatedEmployees.Add(employee);
            } else {

                Console.WriteLine($"Employee {employeeData[1]} with ID {employeeData[0]} has been deleted.");
                employeeFound = true;
            }
        }

        if (!employeeFound){   
            Console.WriteLine($"No employee found with ID {employeeID}.");
            return;
        }

    }

}

程序.cs

List<Employee> employeeList = new List<Employee>();


bool quit = false;

while (!quit)
{
    try
    {
        displayOptions();

        string input = Console.ReadLine();
        Console.WriteLine();

        switch (input)
        {
            case "1":
                createEmployee();
                    break;
            case "2":
                displayEmployees();
                break;
            case "3":
                employeeIDSearch();
                break;
            case "4":
                employeeNameSearch();
                break;
            case "5":
                deleteEmployeeByID();
                break;
            case "6":
                quit = true;
                break;
            default:
                Console.WriteLine("Invalid input, please try again.");
                break;
        }
    }
    catch (Exception)
    {
        Console.WriteLine("Please choose one of the inputs!");
    }
}

void displayOptions()
{
    Console.WriteLine();
    Console.WriteLine("Please select an option below:");
    Console.WriteLine("---------------------------");
    Console.WriteLine("1. Create New Employee");
    Console.WriteLine("2. View All Employees");
    Console.WriteLine("3. Search Employee by ID");
    Console.WriteLine("4. Search Employee by Name");
    Console.WriteLine("5. Delete Employee");
    Console.WriteLine("6. Quit");
    Console.WriteLine("---------------------------");
}

//Option 1: Create New Employee
void createEmployee(){
        Console.Write("Enter employee name: ");
        string name = Console.ReadLine();

        Console.Write("Enter employee title: ");
        string title = Console.ReadLine();

        DateTime startDate;
        while (true)
        {
            Console.Write("Enter employee start date (MM/DD/YYYY): ");
            if (DateTime.TryParse(Console.ReadLine(), out startDate))
            {
                break;
            }
            Console.WriteLine("Invalid date format. Please enter the date in MM/DD/YYYY format.");
        }
    
    Employee newEmp = new Employee(name, title, startDate);
    newEmp.CreateNewEmployee(name, title, startDate);
    employeeList.Add(newEmp);
        
}


//Option 2: Display all Employees
void displayEmployees()
{
    if (employeeList.Count == 0)
        {
            Console.WriteLine("No contacts to display.");
            return;
        }
        foreach (Employee employee in employeeList) {
            employee.printDetails();
            Console.WriteLine();
           }
}

//Option 3: Search Employee by ID
void employeeIDSearch(){
    int empID;
    while (true){
        Console.WriteLine("Enter Employee ID:");
        if (int.TryParse(Console.ReadLine(), out empID)){
            Employee.employeeIDSearch(empID);
            break;
        }
        else{
            Console.WriteLine("Invalid Input");
            break;
        }
    }
}

//Option 4: Search Employee by Name
void employeeNameSearch(){

    Console.WriteLine("Enter Employee Name:");
    string name = Console.ReadLine();
    Employee.employeeNameSearch(name);
    

}

//Option 5: Delete Employee
void deleteEmployeeByID(){

    int IDNum;
        while (true) {
            Console.WriteLine("Enter employee ID to search: ");
            if (int.TryParse(Console.ReadLine(), out IDNum)){
                break;
            }
            Console.WriteLine("Invalid employee ID. Try again.");
        }
        Employee.deleteEmployeeByID(IDNum);
}




我已经对控制台程序进行了一些调整,目前我仍在对其进行调整,以使其按我的预期工作。这不是最终产品!

c# methods console-application overloading streamwriter
© www.soinside.com 2019 - 2024. All rights reserved.