簡體   English   中英

C#創建一個類列表<> / Dictionary <>,作為數據庫寫入.txt文件並從中讀取,而不會覆蓋數據

[英]C# Creating a Class List<>/Dictionary<>, writing to and reading from .txt file as a database without overwriting data

這是你們到這里來最常見的問題之一,請原諒我,但是無論我怎么努力搜尋,我都無法克服。

我正在為Windows Forms Application中的項目構建鑰匙串應用程序,為了盡可能容易地理解此概念,我使用List <>而不是Dictionary // iList

這是我一直在使用的類:

public class Account
{
    public static List<Account> myAccountList = new List<Account>();
    public string Domain; //this is supposed to be google/skype/facebook
    public string Email;
    public string Username;
    public string Password;

    public Account (string domain, string email, string username, string password)
    {
        Domain = domain;
        Email = email;
        Username = username;
        Password = password;
        myAccountList.Add(new Account(domain, email, username, password)); //constructor calls the new list instance
    }
    private static void SaveToFile()
    {
        System.IO.File.WriteAllLines(@accountdb.txt, myAccountList);
    }
    private static void ReadFromFile() // this is meant to be used as authentication in my main form, it isn't necessary right now..
    {
        System.IO.File.ReadAllLines(@accountdb.txt);
    }
}

我對此有幾個問題:

  1. 我無法創建功能性的Save方法寫入文件,我在System.IO嘗試了幾種方法
  2. 當我將列表更改為一維數組時,它將不斷覆蓋它,我想模擬MySQL以使自己熟悉以備后用。

調用構造方法的Button Click事件:

private void buttonSave_Click(object sender, EventArgs e)
    {
        string domain, email, username, password;
        domain = comboboxDomain.Text;
        email = textboxEmail.Text;
        username = textboxUsername.Text;
        password = textboxPassword.Text;
        //Checking for correct EMAIL

        if (!textboxEmail.Text.Contains("@") && (!textboxEmail.Text.Contains(".")))
        {
            MessageBox.Show("Invalid Email Format");
        }
        else
        {
            Account account = new Account(domain, email, username, password);
        }
    }

根據您的評論,聽起來您想追加而不是撰寫 如果要追加到文件(即添加到已有文件),則需要使用AppendAllLines()函數。

但是,您遇到的問題更大,因為您正在嘗試將對象列表而不是字符串寫入文件。 如果您只想編寫密碼,則需要這樣做:

private static void SaveToFile()
{
    System.IO.File.AppendAllLines("path/to/file", myAccountList.Select(x => x.Password));
}

如果存在,此方法將追加到文件中;如果不存在,則僅創建一個新文件。

這里的文件

WriteAllLines期望將string[]作為第二個參數。 因此,您需要創建一種將單個Account對象表示為字符串的方法。 最簡單的方法是覆蓋ToString方法。 然后使用Linq Select方法選擇它們。

另外,如果Account類不包含帳戶列表,則更好。 那真的應該是一個單獨的類。 嘗試這樣的事情:

void Main()
{
    var accountList = new AccountList();

    //Save a few accounts to the file
    Account a1 = new Account("Google", "GoogleEmail", "GoogleUser", "GooglePass");
    accountList.Add(a1);
    Account a2 = new Account("Netflix", "NetflixEmail", "NetflixUser", "NetflixPass");
    accountList.Add(a2);

    AccountList.SaveToFile(@"g:\test\accounts.txt", accountList);


    //Load the accounts from the file
    AccountList aList2 = AccountList.ReadFromFile(@"g:\test\accounts.txt");
    aList2.Dump();
}

public class AccountList
{
    private List<Account> accounts;
    public IEnumerable<Account> Accounts { get { return accounts;} }

    public AccountList()
    {
        this.accounts = new List<Account>();
    }

    public void Add(Account a)
    {
        accounts.Add(a);
    }

    public static void SaveToFile(string filename, AccountList accounts)
    {
        //Selects all the `Account` instances and creates a string[]
        System.IO.File.WriteAllLines(filename, accounts.Accounts.Select(a => $"{a}").ToArray());
    }

    public static AccountList ReadFromFile(string filename) // this is meant to be used as authentication in my main form, it isn't necessary right now..
    {
        var result = new AccountList();

        //Read each line from the file and create an Account instance.
        foreach (var line in System.IO.File.ReadAllLines(filename))
        {
            if (!string.IsNullOrWhiteSpace(line))
            {
                var parts = line.Split(',');
                if (parts.Length == 4)
                {
                    Account a = new Account(parts[0], parts[1], parts[2], parts[3]);
                    result.Add(a);
                }
            }
        }

        return result;
    }
}

public class Account
{
    public string Domain; //this is supposed to be google/skype/facebook
    public string Email;
    public string Username;
    public string Password;

    public Account(string domain, string email, string username, string password)
    {
        Domain = domain;
        Email = email;
        Username = username;
        Password = password;
    }

    public override string ToString()
    {
        return $"{Domain},{Email},{Username},{Password}";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM