我似乎無法弄清楚最新的錯誤。當按下'Next'按鈕時,我想從隨機的.txt文件中讀取數據,然後在索引3處顯示數組allLines []中包含的字符串。它似乎只打印該文件的索引,而不是隨機選擇另一個文件讀取。這只是一個小程序,可以幫助我使用閃存卡進行學習。我猜可能有一個我可以下載,但任何想法?顯示隨機打開的文本文件中的行
namespace MSU_Flash_Cards
{
public partial class Form1 : Form
{
DirectoryInfo di = new DirectoryInfo("C:\\Users\\Public\\cards\\");
Random rand = new Random();
int cardside;
int filecount;
int fileindex;
string[] filename;
string[] allLines;
// allLines[0] is for Card Name
// allLines[1] is for Card Description
// allLines[2] is for Card Front
// allLines[3] is for Card Back
public Form1()
{
InitializeComponent();
cardside = 0;
}
private void btnNewCardSave_Click(object sender, EventArgs e)
{
int x = 0;
//store the text in the text boxes in an array
string[] s_temp = new String[4];
s_temp[0] = txtboxNewCardName.Text.ToString();
s_temp[1] = txtboxNewCardDesc.Text.ToString();
s_temp[2] = txtboxNewCardFront.Text.ToString();
s_temp[3] = txtboxNewCardBack.Text.ToString();
StreamWriter sw = new StreamWriter(string.Format("C:\\Users\\Public\\cards\\{0}.txt", s_temp[0])); // s_temp[0] is used here to define the file name to use.
while (x <= 3)
{
//write each segment of the array to a file, lines from 0-3
sw.WriteLine(s_temp[x].ToString());
x++;
}
sw.Close();
}
private void btnNext_Click(object sender, EventArgs e)
{
// Randomly get the next card
SetNextCard();
// Display the next cards 'back'
txtboxCard.Text = string.Format("{0}", allLines[3]);
}
private void btnFlip_Click(object sender, EventArgs e)
{
if (cardside == 0)
{
// if the front is showing, switch to the back
txtboxCard.Text = string.Format("{0}", allLines[3]);
cardside = 1;
}
else
{
// if the back is listed, switch to the front
txtboxCard.Text = string.Format("{0}", allLines[2]);
cardside = 0;
}
}
private void SetNextCard()
{
int x = 0;
// Check the directory for files & count them
FileInfo[] rgFiles = di.GetFiles("*.*");
filecount = di.GetFiles().Length;
// Create a new array based on the filecount
filename = new String[filecount];
// Save each file name in the array
foreach (FileInfo fi in rgFiles)
{
filename[x] = fi.FullName;
x++;
}
// Select randomly a file for reading
fileindex = rand.Next(0, filecount);
// Read each line of the file and assign to a global array for use later
allLines = File.ReadAllLines(string.Format("{0}", filename));
}
}
}
你有沒有試圖通過調試器中的代碼? – svick 2012-02-23 02:26:05
我做到了。 int filecount正確表示文件夾中的文件數量,但文件名不會更改。也許我只是累了,想念一些明顯的東西。雖然我仍然很新。 – user1227317 2012-02-23 02:30:26
一個注意事項:使用'string.Format'就沒什麼意義,就像你經常使用它。 'txtboxCard.Text = string.Format(「{0}」,allLines [3]);'可以簡單地寫成'txtboxCard.Text = allLines [3];' – 2012-02-23 02:30:52