C#在RichTextBox上使用LoadFile或ReadallLines

时间:2014-03-10 13:19:23

标签: c# richtextbox

我在一些系统上遇到问题,当我们尝试加载RichTextBox时程序没有响应,我们无法做任何事情,必须通过Taskmanager杀死它。 它在大多数系统上工作,但是在不同国家的一些系统似乎存在问题。

我们尝试了一些简单的事情:

private void testing4()
{
    richTextBox1.LoadFile(@"C:\testing.logs", RichTextBoxStreamType.PlainText);
}

如果我们决定使用普通的TextBox,它似乎正在使用.net 4.5,但它仍然没有响应。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助:

foreach(var line in File.ReadLines(@"C:\testing.logs"))
{
  richTextBox1.AppendText(line+Environment.NewLine);
}

答案 1 :(得分:0)

由于您使用的是框架4.5,因此您可以像在MSDN示例中那样执行异步操作:

public async void ReadFile()
{
    string filePath = @"C:\testing.logs";

    if (File.Exists(filePath) == false)
    {
        Debug.WriteLine("file not found: " + filePath);
    }
    else
    {
        try
        {
            string text = await ReadTextAsync(filePath);
            richTextBox1.AppendText(text);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
}

private async Task<string> ReadTextAsync(string filePath)
{
    using (FileStream sourceStream = new FileStream(filePath,
        FileMode.Open, FileAccess.Read, FileShare.Read,
        bufferSize: 4096, useAsync: true))
    {
        StringBuilder sb = new StringBuilder();

        byte[] buffer = new byte[0x1000];
        int numRead;
        while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
        {
            string text = Encoding.Unicode.GetString(buffer, 0, numRead);
            sb.Append(text);
        }

        return sb.ToString();
    }
}

来源:Using Async for File Access