C# 将文件加载到richtextbox中

C# 将文件加载到richtextbox中,c#,C#,现在,我的代码设置为,当单击此按钮时,它将打开一个选择文件对话框,并允许用户选择要打开的文件 private void button1_Click(object sender, System.EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { richTextBox1.LoadFile(openFileDialog

现在,我的代码设置为,当单击此按钮时,它将打开一个选择文件对话框,并允许用户选择要打开的文件

private void button1_Click(object sender, System.EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText);
            }
        }
但是-我已经更改了我的程序,因此程序只输出到默认文件,如下所示-

public void CreateInventory(CreateInventory createinventory)
{
    try
    {
        FileStream fileStream = new FileStream
        ("CreateInventory.bin", FileMode.Create,
        FileAccess.Write);
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize(fileStream, createinventory);
        fileStream.Close();
    }
    catch (ItemNotFoundException)
    {
        throw new ItemNotFoundException("Output not created - see logs");
    }
}

如何切换按钮,使其直接加载该文件,而不是要求用户选择要加载的文件?

我不太明白您的问题是什么,请告诉我您想做什么

但我建议您更改代码:

public void CreateInventory(CreateInventory createinventory)
    {
        try
        {
            using (FileStream fileStream = new FileStream("CreateInventory.bin", FileMode.Create, FileAccess.Write))
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fileStream, createinventory);
            }
        }
        catch (Exception ex)
        {
            throw new ItemNotFoundException("Output not created - see logs", ex);
        }
    }
  • 您不应该捕获异常并重新抛出相同的异常-您会丢失宝贵的信息(例如stacktrace)。如果异常在调用方的视图中不正确,您可以像我在上面的代码中那样包装它

  • 在using语句中放置一次性(实现
    IDisposable
    )类非常重要

  • 为什么使用“使用”?

    一次性类包含非托管资源(在本例中为文件句柄),它们不会像托管资源一样释放。你应该在完成后释放它。使用还有另一个优点:即使在范围结束或发生异常时,它也会为您调用
    Dispose()
    。文件已发布,其他进程可以访问该文件