何が間違っているのか分かりません。 'Next'ボタンを押すとランダムな.txtファイルから読み込み、次に配列allLines []に含まれる文字列をインデックス3に表示します。そのファイルのインデックスを出力し、別のものをランダムに選択しないように見えます読み込むファイルこれはフラッシュカードを使って勉強するのに役立つちょっとしたプログラムです。私はダウンロードできるものがあるかもしれないと思うけど、どんなアイディアですか?ランダムに開いたテキストファイルの行を表示
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
しました。 int filecountはフォルダ内のファイル数を正しく表しますが、ファイル名は変わりません。たぶん、私はちょうど疲れて、何かが明らかでない。私はまだこれでもかなり新しいです。 – user1227317
注意: 'string.Format'の使用方法は、あなたがよく使っている方法ではありません。 'txtboxCard.Text = string.Format(" {0} "、allLines [3]);'単に 'txtboxCard.Text = allLines [3];' –