2017-07-18 1 views
0

これはあなたがここで取得する最も一般的な質問の1つですが、どんなに難しい検索をしても。私は、Windowsでのプロジェクトのためのキーチェーンアプリケーションを構築していC#クラスリストの作成<>/Dictionary <>、データを上書きせずにデータベースとしての.txtファイルへの書き込みと読み取り

フォームアプリケーション、そしてできるだけ容易この概念を理解する目的のために私は、これはむしろ辞書//は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. 私はFiに書き込むための機能Saveメソッドを作成することはできません。 le、私はいくつかの方法を試しましたSystem.IO
  2. リストを1次元配列に変更しても、それは絶えず上書きされます。後でMySQLをシミュレートしたいと思います。

コンストラクタを呼び出すボタンの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); 
     } 
    } 
+0

あなたの質問は何ですか? – maccettura

+0

@maccetturaリストをファイルに書き込む方法が間違っていて、保存メソッドが.txtファイルの以前の資格情報を上書きしないようにする方法 –

答えて

0

WriteAllLinesは、2番目のパラメータとして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}"; 
    } 
} 
+0

これは私の現在の理解のために信じられないほど上手ですが、私はそれが正しいとマークするように他の人に役立つだろうということは間違いありません。ありがとう –

0

あなたのコメントによると、あなたが追記ない書き込みにしたいように、それが聞こえます。ファイルに追加したい場合(つまり、そこにwhatsを追加する場合)、AppendAllLines()関数を使用する必要があります。

ただし、文字列ではなくオブジェクトのリストをファイルに書き込もうとしているため、大きな問題があります。あなただけのパスワードを書きたい場合は、この必要があります。

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

それが存在する場合、このメソッドは、それが存在しない場合、それは単に新しいファイルを作成し、ファイルに追加します。

ドキュメントhere

+0

これはコンパイルされません。 –

+0

@ S.Nog私は自分の答えを更新しました。IEnumerable をファイルに書き込もうとしていました。私は_your_コードをコンパイルしたと仮定しました。 – maccettura

+0

これは.txtファイルを作成するようですが、実際には 'Password'文字列をファイルに書き出すわけではありません。そして、はい、それは最初からコンパイルされていませんでした、私はそれを明確にすべきでした。 –

関連する問題