现在,我的文本文件包含以下数据:
4
3
2
1
我的程序能够读取数据并将其转换为整数。
我在尝试单击按钮时将各自的数据增加+1并将其写入文本文件时遇到问题。
如果(请求[“提交”] ==“ vote_kim”)
当用户单击“ vote_kim”按钮时,我尝试使用上述代码,程序将+1到文本文件中的第一个值,但是当我检查文件时,数据未写入。我在这里我做错了什么,应该改变什么?
@{
var result = "";
string[] userData = null;
int[] votes = null;
char[] delimiterChar = { ',' };
var lines = "";
var dataFile = Server.MapPath("~/App_Data/data.txt");
if (File.Exists(dataFile))
{
userData = File.ReadAllLines(dataFile);
votes = Array.ConvertAll(userData, int.Parse);
if (userData == null)
{
// Empty file.
result = "The file is empty.";
}
}
else
{
// File does not exist.
result = "The file does not exist.";
}
if (IsPost)
{
if (Request["submit"] =="vote_kim")
{
votes[0] += 1;
for (int i = 0; i < votes.Length; i++)
{
lines = votes[i] + Environment.NewLine;
File.AppendAllText(@dataFile, lines);
result = "Your vote has been saved.";
}
}
}
//votes[0] += 1;
}
<!DOCTYPE html>
<html>
<head>
<title>Task 3</title>
</head>
<body>
<form id="form1" method="post">
<div>
<table>
<tr>
<td>Kim</td>
<td><input id="vote_kim" type="submit" name="vote_kim" value="vote_kim" /></td>
<td>@votes[0]</td>
</tr>
<tr>
<td>Tom</td>
<td><input id="vote_tom" type="submit" name="vote_tom" value="vote_tom" /></td>
<td>@votes[1]</td>
</tr>
<tr>
<td>Jerry</td>
<td><input id="vote_jerry" type="submit" name="vote_jerry" value="vote_jerry" /></td>
<td>@votes[2]</td>
</tr>
<tr>
<td>Eric</td>
<td><input id="vote_eric" type="submit" name="vote_eric" value="vote_eric" /></td>
<td>@votes[3]</td>
</tr>
</table>
</div>
<div>
@if (result != "")
{
<p>Result: @result</p>
}
</div>
</form>
</body>
</html>