单击从本地PC上传文件后如何设置FileName?

时间:2017-03-29 12:32:31

标签: c# fileopendialog

我有一些简短的代码:

Calendar.current.component(.hour, from: date)

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

但它不起作用。

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

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

以下是microsoft的一个例子

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);
                }
            }
        }



  
        }
    }