2015-09-26 35 views
-3

我已經收集了一個代碼在c#中用於瀏覽窗口中的文件和文件夾。我的示例代碼段如下:在使用C#在窗口瀏覽文件中出現錯誤

void ButtonbrowseOnClick(object obj, EventArgs ea) 
{ 
    int size = -1; 
    DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog. 
    if (result == DialogResult.OK) // Test result. 
    { 
     string file = openFileDialog1.FileName; 
     try 
     { 
      string text = File.ReadAllText(file); 
      size = text.Length; 
     } 
     catch (IOException) 
     { 
     } 
    } 
    Console.WriteLine(size); // <-- Shows file size in debugging mode. 
    Console.WriteLine(result); // <-- For debugging use. 
} 

不過,我收到以下錯誤:

The name 'openFileDialog1' does not exist in the current context  

什麼是錯的代碼段?

回答

3

您確定您定義了openFileDialog1?將方法的第二行更改爲波紋管似乎可以解決問題

void ButtonbrowseOnClick(object obj, EventArgs ea) 
{ 
    int size = -1; 
    OpenFileDialog openFileDialog1 = new OpenFileDialog(); //define the variable 
    DialogResult result = openFileDialog1.ShowDialog(); 

    //your code 
+0

解決發生在System.Windows.Forms.dll中@Hossein Narimani拉德 – ACE

+1

錯誤,但得到follwing例外 型「System.Threading.ThreadStateException」未處理的異常你能否提供更多信息,請項目類型?它是一個Windows窗體應用程序? –

+0

是@Hossein Narimani Rad – ACE

3

它不存在,因爲它尚未定義。

OpenFileDialog openFileDialog1 = new OpenFileDialog();

相關問題