Karim Zibari
Karim Zibari

Reputation: 19

Listing current directory does not contain copied file

After copying a file using File.Copy, current directory listing does not contain the copied file:

string path = Directory.GetCurrentDirectory();
string[] files = Directory.GetFiles(path);
Console.WriteLine("Enter the name of the file to copy");
source = Console.ReadLine();
Console.WriteLine("Enter a name for the new file:");
string target = Console.ReadLine();
File.Copy(source, target);
Console.WriteLine("\n\nNew listing:");
foreach (var file in files)
       Console.WriteLine(file);

Upvotes: 1

Views: 43

Answers (2)

Oladhamzeh
Oladhamzeh

Reputation: 13

change your code to this:

    string path = Directory.GetCurrentDirectory();
string[] files = Directory.GetFiles(path);
Console.WriteLine("Enter the name of the file to copy");
source = Console.ReadLine();
Console.WriteLine("Enter a name for the new file:");
string target = Console.ReadLine();
File.Copy(source, target);
Console.WriteLine("\n\nNew listing:");

files = Directory.GetFiles(path); //this added

foreach (var file in files)
       Console.WriteLine(file);

Upvotes: 0

iakobski
iakobski

Reputation: 1274

files won't get updated until you call files = Directory.GetFiles(path); again.

It is an array that is filled from the call to GetFiles, not a link to the directory itself.

Upvotes: 6

Related Questions