【问题标题】:Can't append a list to an existing file. C#无法将列表附加到现有文件。 C#
【发布时间】:2021-02-11 16:41:18
【问题描述】:

**我有一个现有的 .txt 文件,我想用它来存储我的数据,但是在使用此代码时,我在 switch case 1 的第 39 行遇到错误。我是 stackoverflow 和一般编码的新手所以,如果我犯了一些错误,请原谅:) **

using System;
using System.Collections.Generic;
using System.IO;

class Program
{

    public static List<Pw> Site = new List<Pw>();
    static void Main(string[] args)
    {

        string file = @"C: \Users\james\Documents\DataFolder\Vault.txt";
        
        string command = "";
        while (command != "exit")
        {
            Console.Clear();
            Console.WriteLine("Please enter a command: ");
            command = Console.ReadLine().ToLower();
            switch (command)
            {
                case "1":
                    AddPw();                        
                    File.AppendAllLines(file, Pw.Site);
                    

                    break;
                  
                case "2":
                    
                    if (File.Exists(file))
                    {
                        // Read all the content in one string 
                        // and display the string 
                        string str = File.ReadAllText(file);
                        Console.WriteLine(str);
                    }
                    break;
            }
        }


    }
    private static void AddPw()
    {
        Pw pw = new Pw();

        Console.Write("Enter the Username/Email: ");
        pw.Username = Console.ReadLine();

        Console.Write("Enter Full Name: ");
        pw.FullName = Console.ReadLine();

        Console.Write("Enter Phone Number: ");
        pw.PhoneNumber = Console.ReadLine();

        Console.Write("Enter Your Password: ");
        string password = Console.ReadLine();
        pw.Password = password;

        Site.Add(pw);
    }

    private static void PrintPw(Pw pw)
    {
        Console.WriteLine("Username/Email: " + pw.Username);
        Console.WriteLine("Full Name: " + pw.FullName);
        Console.WriteLine("Phone Number: " + pw.PhoneNumber);
        Console.WriteLine("Password: " + pw.Password[0]);
        Console.WriteLine("-------------------------------------------");
    }

    private static void ListPw()
    {
        if (Site.Count == 0)
        {
            Console.WriteLine("Your address book is empty. Press any key to continue.");
            Console.ReadKey();
            return;
        }
        Console.WriteLine("Here are the current people in your address book:\n");
        foreach (var pw in Site)
        {
            PrintPw(pw);
        }
        Console.WriteLine("\nPress any key to continue.");
        Console.ReadKey();
    }


         
}

public class Pw
{
    public string Username { get; set; }
    public string FullName { get; set; }
    public string PhoneNumber { get; set; }
    public string Password { get; set; }
}

【问题讨论】:

  • 欢迎您,能否请您附上错误消息并告诉我们您已经尝试过什么?似乎 Pw 不包含 Site 属性。

标签: c# list file append write


【解决方案1】:

我已经更新了您现有的功能。
使用此功能,您可以在现有文件中添加和附加数据。


private static void AddPw(string filePath)
{
    try
    {
        Pw pw = new Pw();
        if (!File.Exists(filePath))
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
            {
                Console.Write("Enter the Username/Email: ");
                pw.Username = Console.ReadLine();
                sw.WriteLine(pw.Username);

                Console.Write("Enter Full Name: ");
                pw.FullName = Console.ReadLine();
                sw.WriteLine(pw.FullName);

                Console.Write("Enter Phone Number: ");
                pw.PhoneNumber = Console.ReadLine();
                sw.WriteLine(pw.PhoneNumber);

                Console.Write("Enter Your Password: ");
                pw.Password = Console.ReadLine();
                sw.WriteLine(pw.Password);
            }
        }
        else
        {
            
            using (StreamWriter sw = File.AppendText(filePath))
            {
                Console.Write("Enter the Username/Email: ");
                pw.Username = Console.ReadLine();
                sw.WriteLine(pw.Username);

                Console.Write("Enter Full Name: ");
                pw.FullName = Console.ReadLine();
                sw.WriteLine(pw.FullName);

                Console.Write("Enter Phone Number: ");
                pw.PhoneNumber = Console.ReadLine();
                sw.WriteLine(pw.PhoneNumber);

                Console.Write("Enter Your Password: ");
                pw.Password = Console.ReadLine();
                sw.WriteLine(pw.Password);
            }
        }
    }
    catch (Exception ex)
    {
    }
}

【讨论】:

    【解决方案2】:
    File.AppendAllLines(file, Pw.Site);
    

    在这一行中,您需要传递一个 IEnumerable 才能使 AppendAllLines 工作。您可以使用 ConvertAll 方法轻松地将站点(List&lt;Pw&gt;)转换为IEnumerable&lt;string&gt;。这是实现这一目标的一种方法:

    用这个替换那行:

    File.AppendAllLines(file, Site.ConvertAll<string>(
      (p) => string.Format("{0} | {1} | {2} | {3}\n", 
        p.Username, 
        p.FullName, 
        p.PhoneNumber, 
        p.Password
      ))
    );
    

    这个“lambda”基本上接受你的 Pw 对象并将其转换为内联字符串。

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 2017-06-30
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多