用c#在网页中创建浏览按钮

本文关键字:创建 浏览 按钮 网页 | 更新日期: 2023-09-27 18:07:25

我创建了一个网页,并在其中创建了一个名称为"BrowseButton"的浏览按钮和一个名称为"BrowseTextBox"的文本框

后端代码为:

protected void BrowseButtonClick(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.ShowDialog();
            BrowseTextBox.Text = openFileDialog1.FileName;
        }

但是我得到了一个ThreadStateException,我不知道如何处理....

用c#在网页中创建浏览按钮

你说你正在创建一个网页,但你的代码使用OpenFileDialog类从Windows窗体或WPF库。这些对话框不能在web应用程序中使用——它们只能在编写Windows应用程序时使用。您所看到的线程错误就是由此直接导致的。

你不能做任何关于这个异常:没有办法在一个web应用程序中使用这些类。相反,如果你想上传一个文件,你应该看看HTML的<input type="file"元素,或者也许是在ASP.NET中的FileUpload控件。

这是行不通的,因为FolderBrowserDialog弹出的唯一方式是Server-Side,所以程序将永远等待输入。

你应该使用更适合你需要的Web控件

来自MSDN示例

 protected void UploadButton_Click(object sender, EventArgs e)
{
    // Save the uploaded file to an "Uploads" directory
    // that already exists in the file system of the 
    // currently executing ASP.NET application.  
    // Creating an "Uploads" directory isolates uploaded 
    // files in a separate directory. This helps prevent
    // users from overwriting existing application files by
    // uploading files with names like "Web.config".
    string saveDir = @"'Uploads'";
    // Get the physical file system path for the currently
    // executing application.
    string appPath = Request.PhysicalApplicationPath;
    // Before attempting to save the file, verify
    // that the FileUpload control contains a file.
    if (FileUpload1.HasFile)
    {
        string savePath = appPath + saveDir +
            Server.HtmlEncode(FileUpload1.FileName);
        // Call the SaveAs method to save the 
        // uploaded file to the specified path.
        // This example does not perform all
        // the necessary error checking.               
        // If a file with the same name
        // already exists in the specified path,  
        // the uploaded file overwrites it.
        FileUpload1.SaveAs(savePath);
        // Notify the user that the file was uploaded successfully.
        UploadStatusLabel.Text = "Your file was uploaded successfully.";
    }
    else
    {
        // Notify the user that a file was not uploaded.
        UploadStatusLabel.Text = "You did not specify a file to upload.";   
    }

我不认为我能比他们解释得更好。