4

解決策についてはコメントを参照してください -- ファイルが間違った場所にありました

あちこちで答えを探しましたが、見つけることができませんでした。他のプログラミング言語でファイルからの読み取りにこれほど苦労したことはなかったので、これは私にとって本当にイライラします。

基本的なインスタント メッセージング プログラムのテキスト ファイルからユーザー名とパスワードを抽出しようとしています。すべてのコードを掲載するつもりはありません。長すぎます。また、テキスト ファイルはプログラムの最初に読み取られるため、関係ない可能性が高いです。

読み込もうとしているテキスト ファイル ("users.ul") の内容は次のとおりです。

admin.password
billy.bob
sally.sal

テキスト ファイルから読み取るコードは次のとおりです。

users = new Dictionary<string, User>();

System.Console.WriteLine("users.ul exists: " + File.Exists("users.ul"));

// Check the status of users.ul. If it exists, fill the user dictionary with its data.
if (File.Exists("users.ul"))
{
    // Usernames are listed first in users.ul, and are followed by a period and then the password associated with that username.
    StreamReader reader = new StreamReader("users.ul");
    string line;
    int count = 0;

    while ((line = reader.ReadLine()) != null)
    {
        string[] splitted = line.Split('.');
        string un = splitted[0].Trim();
        string pass = splitted[1].Trim();

        User u = new User(un, pass);

        // Add the username and User object to the dictionary
        users.Add(un, u);

        count++;
    }

    System.Console.WriteLine("count: " + count);

    reader.Close();
}

これは私のコードが生成する出力です:

users.ul exists: True
count: 1

ユーザー辞書に追加されるデータは、パスワードが「password」の「admin」のみです。他の行は無視されます。

ここで私を助けてください。私のプログラムは、複数のユーザーがいないと役に立ちません。このサイトの他の同様の質問を含め、どこでも解決策を探しました。ファイルからの読み取りがこれほど多くの時間を無駄にすることになるとは思いもしませんでした。

4

2 に答える 2

10

StreamReader を使用する厳密な手順を実行する必要がある場合を除き、File.ReadAllLines()(列挙可能な) 文字列配列を返す を使用することをお勧めします。

いっそのこと、linqを使用してください:-)

System.Console.WriteLine("users.ul exists: " + File.Exists("users.ul"));

// Check the status of users.ul. If it exists, fill the user dictionary with its data.
if (File.Exists("users.ul")) {
    var lines = File.ReadAllLines("users.ul");
    // Usernames are listed first in users.ul, and are followed by a period
    // and then the password associated with that username.
    var users = lines.Select(o => o.Split('.'))
                     .Where(o => o.Length == 2)
                     .Select(o => new User(o[0].Trim(), o[1].Trim());

    System.Console.WriteLine("count: " + users.Count());
}
于 2013-03-15T21:55:58.670 に答える
5

これをワンライナーにリファクタリングしたいという誘惑に抵抗できませんでした:

var users = File.ReadAllLines("users.ul").Select(l => new User(l.Substring(0, l.IndexOf('.')), l.Substring(l.IndexOf('.') + 1))).ToDictionary(u => u.Name);
于 2013-03-15T22:05:00.270 に答える