对于我的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;
}
}
答案 0 :(得分:1)
您将数据保存在文件中,不应无限次写入。当您经常请求时,它会以多线程写入文件,线程会锁定文件。 我建议你用try ... catch ...写文件找问题:
public bool CreateAccount(String username, String password)
{
createAccounts();
try
{
sw = File.AppendText(path);
}
catch (Exception ex)
{
throw ex;
}
if (!usernameExists(username))
{
sw.WriteLine(username + "," + password + "\n");
sw.Close();
sw = null;
return true;
}
else
{
sw.Close();
sw = null;
return false;
}
}
答案 1 :(得分:1)
您在createAccounts和usernameExists之间有一个循环。只要data2.Length不为零,你就会无休止地循环。