2012-05-10 112 views
4

试图将一些VB转换为C#...(也学习C#)。 我有一些代码循环通过目录中的文件并检索其文件信息。我原本在VB中,但我试图学习C#,并且在线转换器不会给我通过.net 2.0的代码。如何通过foreach循环获取FileInfo?

以下是错误: Type and identifier are both required in a foreach statement

这里是我的代码:我试图把foreach(FileInfo f...

DirectoryInfo dirInfo = new DirectoryInfo(currentDir); 
FileInfo[] files = null; 
files = dirInfo.GetFiles(); 

FileInfo f = default(FileInfo); 
foreach (f in files) { ... 
} 

,但它给了我一个不同的错误: A local variable named 'f' cannot be declared in this scope because it would give a different meaning to 'f', which is already used in a 'parent or current' scope to denote something else

我如何修理它?

+2

'的foreach语句;你会得到什么错误? – carlosfigueira

+0

在问题中增加了错误。抱歉。我认为这也应该工作,但这是.net2,而不是.net4 - 也许这有所作为? – bgmCoder

+1

只需删除'FileInfo f = default(FileInfo);'因为你不需要初始化迭代变量。 –

回答

13
DirectoryInfo dirInfo = new DirectoryInfo(currentDir); 
FileInfo[] files = null; 
files = dirInfo.GetFiles(); 

// I removed the declaration of f here to prevent the name collision. 
foreach (FileInfo f in files) 
{ ... 
} 

下面是代码的简化版本:

DirectoryInfo dirInfo = new DirectoryInfo(currentDir); 
foreach (FileInfo f in dirInfo.GetFiles()) 
{ 
} 
+0

对不起 - 我刚刚更新了我的问题以反映我收到的错误当使用它。 – bgmCoder

+0

现在重新阅读答案。我已更新它以使其更清楚。 –

+0

就是这样!我会在4分钟内将此标记为已接受。谢谢蒲式耳。我知道我必须阅读一些基础知识(我知道它在VB中,但我不想将所有内容翻译成C#...),但我现在没有时间学习。你们都很有帮助! – bgmCoder

1

您应该提供循环内使用的变量类型。在你的情况下,它将是FileInfo。但随着C#3.0或更高版本,你可以只写var和编译器会推断出类型为您提供:

foreach (FileInfo f in files) 
{ 
    // ... 
} 

了解更多关于foreach语句here

完整的解决方案(你不需要初始化迭代变量和文件的阵列):

DirectoryInfo dir = new DirectoryInfo(currentDir); 
foreach (FileInfo file in dir.GetFiles()) 
{ 
    // use file 
} 
+0

我要下一个SharePoint应用程序运行此F'别的地方,因此.NET 2.0。 var'放弃了这个错误:'无法找到类型或命名空间名'var'(你是否缺少using指令或程序集引用?)' – bgmCoder

0

这应该工作:

 DirectoryInfo dirInfo = new DirectoryInfo(currentDir); 
     FileInfo[] files = null; 
     files = dirInfo.GetFiles(); 
     foreach (FileInfo f in files) 
     { 
     } 

Ed它:

这将是清洁的,在我看来:

 foreach (FileInfo f in new DirectoryInfo(currentDir).GetFiles()) 
      { 
      } 
+0

为什么要将'null'分配给文件数组? –

+0

我只是修改他的代码,使其工作。 – Kevin

1

这里就是它看起来像你会错:

FileInfo f = default(FileInfo); 
foreach (f in files) { ... 
} 

您正在定义F中的循环之外,并然后试图在循环内定义它。

如果您需要默认为f,试试这个:

FileInfo f = default(FileInfo); 
foreach (FileInfo file in files) 
    { 
     relevant code here 
    } 

否则删除(在文件的FileInfo F)`应该工作在声明变量 “F”