概要
cscの作法、調べてみた。
練習問題やってみた。
練習問題
デスクトップのテキストファイルをgrepせよ。
方針
- テキストボックス使う。
- ボタン使う。
- 結果は、テキストボックスに一行表示。ファイル名:行目:一行
写真
サンプルコード
using System;
using System.Windows.Forms;
using System.Drawing;
using System.IO.Ports;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
public class Searcher {
protected readonly string[] Words;
public Searcher(string[] words) {
Words = words;
}
public virtual bool Search(string line) {
return Words.Any(x => line.Contains(x));
}
}
public static class GrepUtil {
public static Func<string[], Searcher> SearcherFactory = words => new Searcher(words);
public static IEnumerable<String> Grep(TextReader reader, params string[] words) {
var searcher = SearcherFactory(words);
string line;
for (var i = 1; (line = reader.ReadLine()) != null; i++)
if (searcher.Search(line))
yield return i + ": " + line;
}
}
class form1: Form {
private Button button1;
private TextBox textBox1;
private TextBox textBox2;
private TextBox textBox3;
form1() {
Text = "grep";
ClientSize = new Size(500, 500);
textBox1 = new TextBox();
textBox1.Location = new Point(30, 20);
textBox1.Size = new Size(300, 20);
textBox1.Text = "ipv6";
textBox2 = new TextBox();
textBox2.Location = new Point(30, 70);
textBox2.Size = new Size(300, 20);
textBox2.Text = "ping6";
button1 = new Button();
button1.Location = new Point(300, 120);
button1.Text = "grep";
button1.Click += new EventHandler(button1_Click);
textBox3 = new TextBox();
textBox3.Location = new Point(30, 170);
textBox3.Multiline = true;
textBox3.Size = new Size(450, 320);
textBox3.TabIndex = 2;
textBox3.Text = "";
textBox3.AutoSize = false;
textBox3.WordWrap = false;
textBox3.ScrollBars = ScrollBars.Both;
Controls.AddRange(new Control[] {
textBox1,
textBox2,
button1,
textBox3
});
}
private void button1_Click(object sender, EventArgs e) {
string dpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "");
DirectoryInfo di = new DirectoryInfo(dpath);
FileInfo[] files = di.GetFiles("*.txt", SearchOption.TopDirectoryOnly);
foreach (FileInfo f in files)
{
using(StreamReader sr = new StreamReader(f.FullName, Encoding.GetEncoding("Shift_JIS")))
{
string input = sr.ReadToEnd();
using (var str = new StringReader(input))
{
List<string> result = GrepUtil.Grep(str, textBox1.Text, textBox2.Text).ToList();
foreach (var item in result)
textBox3.AppendText(f.FullName + " : " + item + "\r\n");
}
}
}
}
[STAThread]
public static void Main() {
Application.Run(new form1());
}
}
以上。