C# 如何使用 GetFile() 获取文件夹中所有文件的文件信息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17620076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i get the fileinfo of all files in a folder with GetFile()?
提问by Julian
I dont know whats my mistake.
我不知道我的错误是什么。
FileInfo[] FileInformation = DirectoryInfo.GetFiles(textBoxPath.Text);
for (int i = 0; i <= FileInformation.Length; i++)
{
File.Move(FileInformation[i].DirectoryName, FileInformation[i].Directory + "File" + i);
}
VisualSudio says that here is the error:
VisualSudio 说这是错误:
System.IO.DirectoryInfo.GetFiles(textBoxPath.Text);
System.IO.DirectoryInfo.GetFiles(textBoxPath.Text);
采纳答案by Sergey Berezovskiy
DirectoryInfois not a static class (you mixed it with Directorywhich exposes static methods) thus you should create instance of it:
DirectoryInfo不是静态类(您将它与公开静态方法的Directory混合),因此您应该创建它的实例:
var dir = new DirectoryInfo(textBoxPath.Text);
FileInfo[] files = dir.GetFiles();
Also I suggest you to use Path.Combinefor generating new file path and FileInfo.MoveTomethod, which don't require source directory name:
另外我建议你使用Path.Combine生成新的文件路径和FileInfo.MoveTo方法,不需要源目录名:
for(int i = 0; i < files.Length; i++)
{
FileInfo file = files[i];
string destination = Path.Combine(file.DirectoryName, "File", i.ToString());
file.MoveTo(destination);
}
One more thought - if you don't need any additional info about files, besides names, then you can get file names only, without FileInfoobjects creation. Use static methods of Directoryand Fileclasses. That will be more efficient:
再想一想——如果你不需要关于文件的任何额外信息,除了名称,那么你只能获得文件名,而无需FileInfo创建对象。使用Directory和File类的静态方法。这样效率会更高:
string sourceDir = @"D:\Downloads";
string[] files = Directory.GetFiles(sourceDir);
for (int i = 0; i < files.Length; i++)
{
string fileName = files[i];
var destination = Path.Combine(sourceDir, "File", i.ToString());
File.Move(fileName, destination);
}
回答by saamorim
Use the following:
使用以下内容:
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(textBoxPath.Text);
System.IO.FileInfo[] fileInformations = dir.GetFiles();
for (int i = 0; i <= fileInformations.Length; i++)
{
System.IO.File.Move(fileInformations[i].DirectoryName, System.IO.Path.Combine(FileInformation[i].Directory, "File" + i));
}
EDIT:renamed your FileInformationto the properway to write local variable names fileInformations. Used Path.Combineto combine paths and filename instead of using string combination, as this will take care of missing / and other path issues.
编辑:将您重命名FileInformation为写入局部变量名称的正确方式fileInformations。用于Path.Combine组合路径和文件名而不是使用字符串组合,因为这将解决丢失 / 和其他路径问题。

