对于我的 Web 服务课程,我正在尝试创建一个非常简单的登录系统。我遇到了一个问题,即每当调用 checkCredentials 时 createAccounts() 会不断获得无限次。知道为什么吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;
public class Service : IService
{
static String path = @"PATH REMOVED";
List<Account> accounts = new List<Account>();
StreamWriter sw = null;
private void createAccounts()
{
String data = File.ReadAllText(path);
string[] data2 = data.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string[] temp;
for (int i = 0; i < data2.Length; i++)
{
temp = data2[i].Split(',');
if(!usernameExists(temp[0]) && temp[0] != "")
{
accounts.Add(new Account(temp[0],temp[1]));
}
}
}
public bool CreateAccount(String username, String password)
{
createAccounts();
sw = File.AppendText(path);
if (!usernameExists(username))
{
sw.WriteLine(username + "," + password + "\n");
sw.Close();
sw = null;
return true;
}
else
{
sw.Close();
sw = null;
return false;
}
}
public bool usernameExists(String username)
{
createAccounts();
if(accounts.Exists(a => a.username == username))
return true;
else
return false;
}
public bool CheckCredentials(String username, String password)
{
createAccounts();
if (usernameExists(username))
{
if(accounts.Find(a => a.username == username).username == username && accounts.Find(a => a.username == username).password == password)
return true;
else
return false;
}
else
return false;
}
}
class Account
{
public String username;
public String password;
public Account(String u, String p)
{
username = u;
password = p;
}
}