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