C# 在程序启动时用输出文件对话框提示用户(初始化)
我目前正在处理输出文件。我正在构建一个程序,请求用户在程序执行任何其他操作之前保存输出文件。其目的是程序将结果写入此输出文件。我已经能够通过单击按钮来显示“输出文件”对话框。当程序初始化时,是否有其他方法提示用户使用“输出文件”对话框 通过按钮编码输出文件:C# 在程序启动时用输出文件对话框提示用户(初始化),c#,winforms,openfiledialog,C#,Winforms,Openfiledialog,我目前正在处理输出文件。我正在构建一个程序,请求用户在程序执行任何其他操作之前保存输出文件。其目的是程序将结果写入此输出文件。我已经能够通过单击按钮来显示“输出文件”对话框。当程序初始化时,是否有其他方法提示用户使用“输出文件”对话框 通过按钮编码输出文件: namespace open_document { public partial class Form1 : Form { public Form1() { Initi
namespace open_document
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Text Files | *.txt";
openFile.ShowDialog();
StreamReader infile = File.OpenText(openFile.FileName);
}
}
}
您可以使用OnShown:
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Text Files | *.txt";
openFile.ShowDialog();
StreamReader infile = File.OpenText(openFile.FileName); // Don't leave this open!
}
为什么不根据您的要求使用
表单
或页面
的加载
事件:
设计师:
this.Load += new System.EventHandler(this.MainForm_Load);
代码:
您最好的选择可能是将此处理程序中的代码提取到一个不带参数的方法中(您不需要事件传入的任何内容),然后在表单的构造函数或加载事件中调用它。这将在加载表单之前执行您的代码
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Text Files | *.txt";
openFile.ShowDialog();
StreamReader infile = File.OpenText(openFile.FileName);
...
Application.Run(new Form1());
}
}
静态类程序
{
///
///应用程序的主要入口点。
///
[状态线程]
静态void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
OpenFileDialog openFile=新建OpenFileDialog();
openFile.Filter=“Text Files |*.txt”;
openFile.ShowDialog();
StreamReader infle=File.OpenText(openFile.FileName);
...
Application.Run(新Form1());
}
}
您需要关闭StreamReader
。是WinForms吗?如果是,请添加标记并尝试Form Load event您是否询问可以连接哪些事件?您可能需要“窗体”的加载事件:是,这是一个windows窗体。我已经添加了标签
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Text Files | *.txt";
openFile.ShowDialog();
StreamReader infile = File.OpenText(openFile.FileName);
...
Application.Run(new Form1());
}
}