Created
November 21, 2017 01:50
-
-
Save mrgarita/264cbe0045e49afcc33385cbee6db2cd to your computer and use it in GitHub Desktop.
英単語アプリ2:リストを使って単語を管理、起動時ファイル読み込み、終了時ファイル書き出し
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 英単語アプリ2 | |
* 単語リストに単語を追加する | |
* 終了時に単語リストの内容をファイルに書き出す | |
* 起動時にファイルから単語リストを読み込む | |
*/ | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Text; | |
using System.Windows.Forms; | |
namespace 英単語アプリ2 | |
{ | |
public partial class Form1 : Form | |
{ | |
// 単語保存リスト | |
private List<string> tangoList = new List<string>(); | |
// データファイル | |
const string DATAFILE = "tango.txt"; | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
// 単語データを読み込むメソッド | |
private void LoadData() | |
{ | |
try | |
{ | |
// ファイルを読み込み形式で開く | |
StreamReader file = new StreamReader(DATAFILE, Encoding.UTF8); | |
// 読み取ったデータを単語リストに保存しリストボックスに設定 | |
string line = ""; | |
while((line = file.ReadLine()) != null) | |
{ | |
tangoList.Add(line); | |
listBox1.Items.Add(line); | |
} | |
// ファイルを閉じる | |
file.Close(); | |
} catch(Exception e) | |
{ | |
Console.WriteLine(e.Message); | |
} | |
} | |
// 単語データを保存するメソッド | |
private void SaveData() | |
{ | |
try | |
{ | |
// ファイルを書き込み形式で開く | |
StreamWriter file = new StreamWriter(DATAFILE, false, Encoding.UTF8); | |
// 単語リスト1つを1行毎に書き込みをする | |
for (int i=0; i<listBox1.Items.Count; i++) | |
{ | |
file.WriteLine(tangoList[i].ToString()); | |
} | |
// フィアルを閉じる | |
file.Close(); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e.Message); | |
} | |
} | |
// アプリ起動時の処理 | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
// フォーム表示初期設定 | |
this.Text = Application.ProductName; | |
label1.Text = "英単語"; | |
label2.Text = "日本語"; | |
button1.Text = "追 加"; | |
this.ActiveControl = this.textBox1; // textBox1.Focus()はフォームロード時は使えない | |
// データ読み込み | |
LoadData(); | |
} | |
// 単語追加処理 | |
private void button1_Click(object sender, EventArgs e) | |
{ | |
// 未入力なら何もしない | |
if (textBox1.Text == "" || textBox2.Text == "") return; | |
// 英語と日本語をタブ区切り文字列にする | |
string en = textBox1.Text; | |
string ja = textBox2.Text; | |
string tango = en + "\t" + ja; | |
// リストに追加 | |
tangoList.Add(tango); | |
// リストボックスに追加 | |
listBox1.Items.Add(tango); | |
// 追加後テキストボックスをクリア | |
textBox1.Text = textBox2.Text = ""; | |
// フォーカスを移動 | |
textBox1.Focus(); | |
} | |
// アプリ終了時の処理 | |
private void Form1_FormClosing(object sender, FormClosingEventArgs e) | |
{ | |
// データを保存して終了 | |
SaveData(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment