0

我有一些短代码:

private void buttonSave_Click(object sender, EventArgs e) 
{

    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "NHC|*.nhc";
    openFileDialog1.Title = @"test.nhc";

    OpenFileDialog openfiledialog = new OpenFileDialog();
    openfiledialog.ShowHelp = true;
    openfiledialog.FileName = "test.nhc";
    openfiledialog.ShowDialog();
}

我想将 FileName 设置为OpenFileDialog.
例如:我有一个 Web 应用程序,然后单击Upload以从本地 PC 上传文件。OpenFileDialog弹出窗口确实打开了。现在我想test.nhc在字段FileName(Windows 窗口)中将 FileName 设置为,然后单击“打开”。

但它不起作用。

4

2 回答 2

0

您想在点击之前还是之后设置名称?例如,您应该在 PageLoad 中定义此名称。不在点击。

OpenFileDialog openfiledialog = new OpenFileDialog();

protected void Page_Load(object sender, EventArgs e)
{    
         if (!IsPostBack)
         {
            openfiledialog.FileName = "test.nhc";
         }
}

private void buttonSave_Click(object sender, EventArgs e) 
{
          openfiledialog.ShowDialog();
}
于 2017-03-29T12:43:09.110 回答
0

您没有处理打开文件确定按钮的事件。首先,您需要创建一个 Stream 对象,然后创建一个将在 DialogResult.OK 情况下发生的事件。

这是一个来自微软的例子

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "NHC|*.nhc";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Title = @"test.nhc";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            // Insert code to read the stream here.
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }



  
        }
    }

于 2017-03-29T12:43:57.880 回答