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);
}
}
IDisposable
)类非常重要Dispose()
。文件已发布,其他进程可以访问该文件