2015-09-26 69 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();

相关问题