从文件中搜索和阅读

时间:2014-03-05 17:38:32

标签: c#

我想知道是否可以搜索和读取文件并在消息框中显示文件中的内容。

我想通过其ID搜索文件,该ID是用户已知的。当用户输入ID时,我的程序打开共享相同ID的文件; eg.ID.txt在预设文件夹中。

当它被选中时,它会被读取并放入一个MessageBox,然后它将显示文件中的内容。

有人能告诉我怎么做吗? 感谢。

 //Declare variables
    int TID;


    private void TIDFileCreate_Click(object sender, EventArgs e)
    {
        StreamWriter outputFile;
        outputFile = File.CreateText (TID.ToString()+".txt");

        outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
        outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
        outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
        outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
        outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
        outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
        outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
        outputFile.Close();

        MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + "Was Created", "Transaction File");

    }

    private void SearchButton_Click(object sender, EventArgs e)
    {
        SearchID = int.Parse(searchTextBox.Text);
        string[] lines = File.ReadAllLines(@"C:\Users\Public\TestFolder\"+SearchID+".txt");
    }

3 个答案:

答案 0 :(得分:1)

你不能在MessageBox.Show()方法中使用SearchButton_Click吗?

private void SearchButton_Click(object sender, EventArgs e)
{
    SearchID = int.Parse(searchTextBox.Text);
    string[] lines = File.ReadAllLines(@"C:\Users\Public\TestFolder\"+SearchID+".txt");
    System.Windows.Forms.MessageBox.Show(string.Join("\r\n", lines));
}

答案 1 :(得分:0)

我认为你想做什么你应该读到这个: http://msdn.microsoft.com/en-us/library/ms233843.aspx 或者一些关于序列化的类似文章。 这就是说,如果ID的数量增加,你应该考虑采用一个轻量级的DB,即SQLite,只需命名一个。

答案 2 :(得分:0)

看一下DirectoryInfo课程。像下面这样的东西应该做你想要的;

    DirecectoryInfo dir = new DirectoryInfo(pathToRoot);
    FileInfo[] files = dir.GetFiles("Id.txt"); //if using a specific name should return 1 item
    TextBox.Text = File.ReadAllText(files.FirstOrDefault().FullName);

请记住,我没有错误处理或任何事情。您必须自己添加,这只是向您显示获取文件和读取其内容的关键类/方法。还有许多其他选项,例如执行GetFiles(),将该集合保留在内存中,然后再对其进行操作。

相关问题