首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从文本文件导入C# ListBox崩溃

从文本文件导入C# ListBox崩溃
EN

Stack Overflow用户
提问于 2012-11-16 04:15:04
回答 5查看 2.1K关注 0票数 3

我正在使用此代码将文本文件导入到我的ListBox

代码语言:javascript
复制
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "Text Files|*.txt";
        openFileDialog1.Title = "Select a Text file";
        openFileDialog1.FileName = "";
        DialogResult result = openFileDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;

            string[] text = System.IO.File.ReadAllLines(file);
            foreach (string line in text)
            {
                listBox2.Items.Add(line);

            }
            listBox2.Items.Add("");
        }

它适用于10行左右的小文本文件,但当我尝试导入更大的列表(4-5兆字节)时,程序没有响应,它崩溃了。

有什么帮助吗?

EN

回答 5

Stack Overflow用户

发布于 2012-11-16 04:22:10

使用C#中的BufferedStream类可以提高性能。

http://msdn.microsoft.com/en-us/library/system.io.bufferedstream.aspx

票数 2
EN

Stack Overflow用户

发布于 2012-11-16 04:30:26

通过使用此命令:

代码语言:javascript
复制
string[] text = System.IO.File.ReadAllLines(file);
listBox1.Items.AddRange(text);

而不是这样:

代码语言:javascript
复制
string[] text = System.IO.File.ReadAllLines(file);
foreach (string line in text)
{
       listBox2.Items.Add(line);
}

您将使执行速度提高至少10-15倍,因为您不会在每次插入项时都使listBox无效。我已经用几千条线进行了测量。

如果您的文本行数太多,瓶颈也可能是ReadAllLines。即使我不明白你为什么要插入这么多行,用户能找到他/她需要的行吗?

编辑 OK然后我建议你使用BackgroundWorker,下面是代码:

首先初始化BackGroundWorker:

代码语言:javascript
复制
 BackgroundWorker bgw;
        public Form1()
        {
            InitializeComponent();
            bgw = new BackgroundWorker();
            bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
        }

然后在你的方法中调用它:

代码语言:javascript
复制
private void button1_Click(object sender, EventArgs e)
        {
            if (!bgw.IsBusy)
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter = "Text Files|*.txt";
                openFileDialog1.Title = "Select a Text file";
                openFileDialog1.FileName = "";
                DialogResult result = openFileDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    string file = openFileDialog1.FileName;
                    listView1.BeginUpdate();
                    bgw.RunWorkerAsync(file);
                }
            }
            else
                MessageBox.Show("File reading at the moment, try later!");
        }


        void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            listView1.EndUpdate();
        }
        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            string fileName = (string)e.Argument;
            TextReader t = new StreamReader(fileName);
            string line = string.Empty;
            while ((line = t.ReadLine()) != null)
            {
                string nLine = line;
                this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(nLine); });
            }
        }

它会在读取时添加每一行,您将拥有响应式UI,并且行在完成加载之前不会影响listBox。

票数 1
EN

Stack Overflow用户

发布于 2012-11-16 04:22:47

可以使用流来存储数据:

代码语言:javascript
复制
class Test
{

public static void Main()
{
    string path = @"c:\temp\MyTest.txt";

    //Create the file. 
    using (FileStream fs = File.Create(path))
    {
        AddText(fs, "This is some text");
        AddText(fs, "This is some more text,");
        AddText(fs, "\r\nand this is on a new line");
        AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

        for (int i=1;i < 120;i++)
        {
            AddText(fs, Convert.ToChar(i).ToString());

        }
    }

    //Open the stream and read it back. 
    using (FileStream fs = File.OpenRead(path))
    {
        byte[] b = new byte[1024];
        UTF8Encoding temp = new UTF8Encoding(true);
        while (fs.Read(b,0,b.Length) > 0)
        {
            Console.WriteLine(temp.GetString(b));
        }
    }
}

private static void AddText(FileStream fs, string value)
{
    byte[] info = new UTF8Encoding(true).GetBytes(value);
    fs.Write(info, 0, info.Length);
}

}

然后您的事件处理程序

代码语言:javascript
复制
 privateasyncvoid Button_Click(object sender, RoutedEventArgs e)
    {
        UnicodeEncoding uniencoding = new UnicodeEncoding();
        string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";

        byte[] result = uniencoding.GetBytes(UserInput.Text);

        using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))
        {
            SourceStream.Seek(0, SeekOrigin.End);
            await SourceStream.WriteAsync(result, 0, result.Length);
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13405426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档