方法一:系統自帶
<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();
}
}