Reputation: 452
I don't know what's 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);
}
Visual Studio says that here is the error:
System.IO.DirectoryInfo.GetFiles(textBoxPath.Text);
Upvotes: 28
Views: 53380
Reputation: 91
try this code:
var dir = new DirectoryInfo(Y);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
if (file != null)
{
//do whatever with the file
}
}
Upvotes: 0
Reputation: 236268
DirectoryInfo
is not a static class (you mixed it with Directory
which exposes static methods). Thus you should create instance of it:
var dir = new DirectoryInfo(textBoxPath.Text);
FileInfo[] files = dir.GetFiles();
Also I suggest you to use Path.Combine
for generating new file path and FileInfo.MoveTo
method, which don't require source directory name:
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 FileInfo
objects creation. Use static methods of Directory
and File
classes. That will be more efficient:
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);
}
Upvotes: 68
Reputation: 3905
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 FileInformation
to the properway to write local variable names fileInformations
. Used Path.Combine
to combine paths and filename instead of using string combination, as this will take care of missing / and other path issues.
Upvotes: 4