0

我想知道是否有人可以帮助我。我希望能够让我的程序让用户能够只从文本文档中读取某个代码块。但是,我希望将它放在按钮后面,以便可以打开和关闭它。我已经尝试过不同的方法来做到这一点,但没有任何改变。

这就是我的代码目前的样子。

namespace filestream
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string Read(string file)
        {
            StreamReader reader = new StreamReader(file);
            string data = reader.ReadToEnd();
            reader.Close();

            return data;
        }

        private void btn1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                string data = Read(openFileDialog1.FileName);
                textBox1.Text = data;

            }
            else
            {
                //do nothing
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }
    }
}

我对此很陌生,因此将不胜感激任何帮助。

4

3 回答 3

2

据我从你那里看到的,它应该可以工作。我唯一能想到的原因是您的按钮连接到 button1_Click 例程而不是 btn1_Click 例程。如果当您单击按钮时它没有做任何事情,那是我能看到的唯一原因。这段代码看起来是为了让用户选择一个文件,然后读入整个文件并将其放在文本框中。

于 2010-02-23T18:52:21.933 回答
1

如果您可以使用 .Net 3.5 和 LINQ,这里是一个选项...

public static class Tools
{
    public static IEnumerable<string> ReadAsLines(this string filename)
    {
        using (var reader = new StreamReader(filename))
            while (!reader.EndOfStream)
                yield return reader.ReadLine();
    }
}
class Program
{
    static void Main(string[] args)
    {
        var lines = "myfile.txt".ReadAsLines()
                                // you could even add a filter query/formatting
                                .Skip(100).Take(10) //do paging here
                                .ToArray();
    }
}

...扩展疯狂以显示过滤、解析和格式化...

public static class Tools
{
    public static void Foreach<T>(this IEnumerable<T> input, Action<T> action)
    {
        foreach (var item in input)
            action(item);
    }
}
class Program
{
    static void Main(string[] args)
    {
        // the line below is standing in for your text file.  
        // this could be replaced by anything that returns IEnumerable<string>
        var data = new [] { "A 1 3", "B 2 5", "A 1 6", "G 2 7" };

        var format = "Alt: {1} BpM: {2} Type: {0}";

        var lines = from line in data
                    where line.StartsWith("A")
                    let parts = line.Split(' ')
                    let formatted = string.Format(format, parts)
                    select formatted;

        var page = lines.Skip(1).Take(2);

        page.Foreach(Console.WriteLine);
        // at this point the following will be written to the console
        //
        // Alt: 1 BpM: 6 Type: A
        //
    }
}
于 2010-02-23T18:50:01.163 回答
0

你有没有试过btn1_click把它的内容放进去button1_click?有时它对我有用。

于 2011-04-26T09:58:44.530 回答