我试图通过按一个按钮来打开一个文件(更准确地说,这是一个标签,但它的工作方式是一样的)
由于某些原因,当FileDialog打开时,我选择了文件并按下打开,它不会打开文件,它只会关闭FileDialog
private void selectLbl_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = "c:\\";
ofd.Filter = "Script files (*.au3)|*.au3";
ofd.RestoreDirectory = true;
ofd.Title = ("Select Your Helping Script");
if (ofd.ShowDialog() == DialogResult.OK)
{
ofd.OpenFile(); //Not sure if there is supposed to be more here
}
}发布于 2016-05-17 20:03:06
ofd.OpenFile();以字节流的形式返回文件内容,如所述的here。如果要按照所描述的方式打开该文件,请使用
if (ofd.ShowDialog() == DialogResult.OK)
{
System.Diagnostics.Process.Start(ofd.FileName);
}因此,您选择的文件将从关联的应用程序开始。
发布于 2016-05-17 20:08:44
ofd.OpenFile()将用户选择的文件作为Stream打开,您可以使用该use从文件中读取数据。
您如何处理该流取决于您试图实现的目标。例如,您可以读取并输出所有行:
if (ofd.ShowDialog() == DialogResult.OK)
{
using (TextReader reader = new StreamReader(ofd.OpenFile()))
{
string line;
while((line = t.ReadLine()) != null)
Console.WriteLine(line);
}
}或者,如果它是xml文件,则可以将其解析为xml:
if (ofd.ShowDialog() == DialogResult.OK)
{
using(XmlTextReader t = new XmlTextReader(ofd.OpenFile()))
{
while (t.Read())
Console.WriteLine($"{t.Name}: {t.Value}");
}
}发布于 2016-05-17 20:07:34
OpenFileDialog不是用于打开文件的对话框。它只通过一个对话框与操作员通信,如果程序需要知道要打开什么文件,则通常会显示该对话框。所以它只是一个对话框,而不是一个打开文件的工具。
如果用户按下ok或cancel,则由您决定如何操作:
private void selectLbl_click(object sender, ...)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.InitialDirectory = "c:\\";
ofd.Filter = "Script files (*.au3)|*.au3";
ofd.RestoreDirectory = true;
ofd.Title = ("Select Your Helping Script");
var dlgResult = ofd.ShowDialog(this);
if (dlgResult == DialogResult.OK)
{ // operator pressed OK, get the filename:
string fullFileName = ofd.FileName;
ProcessFile(fullFileName);
}
}
}
if (ofd.ShowDialog() == DialogResult.OK)
{
ofd.OpenFile(); //Not sure if there is supposed to be more here
}https://stackoverflow.com/questions/37275490
复制相似问题