C# 文件选择对话框

方法一:系统自带

<asp:FileUpload ID="FileSelect" runat="server" />

方法二:ShowDialog()

直接像以下这样用回报错

"在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式,请确保您的Main函数带有STAThreadAttribute标记。"

public void test(){

OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx|所有文件|*.*";
ofd.ValidateNames = true;
ofd.CheckPathExists = true;
ofd.CheckFileExists = true;

if (ofd.ShowDialog() == DialogResult.OK)

{
 string strFileName = ofd.FileName;
//其他代码
}

}

 

应该这样

Thread invokeThread;
DialogResult selectFileresult;
OpenFileDialog ofd;

public void test(){

ofd = new OpenFileDialog();
ofd.Filter = "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx|所有文件|*.*";
ofd.ValidateNames = true;
ofd.CheckPathExists = true;
ofd.CheckFileExists = true;

invokeThread = new Thread(new ThreadStart(InvokeMethod));

invokeThread.SetApartmentState(ApartmentState.STA);

invokeThread.Start();

invokeThread.Join();
string strFileName = string.Empty;
if (selectFileresult == DialogResult.OK)
{
strFileName = ofd.FileName;
//其他代码
}

private void InvokeMethod()
{
selectFileresult = ofd.ShowDialog();
}

}

 

posted @ 2017-07-19 16:11  公子苏苏苏  阅读(3150)  评论(0编辑  收藏  举报