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

}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM