Anjali
Anjali

Reputation: 2698

moving file from one location to another without knowing file name

One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.

I tried doing this

File.Copy(@"*.xls", @"\\serv44\Application\testing\name\test2\*.xls", true);

It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.

File.Delete("*.xls");

any help will be appreciated

Upvotes: 2

Views: 648

Answers (2)

Tomas Chabada
Tomas Chabada

Reputation: 3019

This should give you that file name:

var fileName = Directory.GetFiles(yourDirectory, "*.xls").ToList().FirstOrDefault();

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

You should get file name and then do whatever you want with that file. I.e. if you have only one xls file in the source directory:

var targetDirectory = @"\\serv44\Application\testing\name\test2\";
var sourceFile = Directory.EnumerateFiles(sourceDirectory, "*.xls").FirstOrDefault();
if (sourceFile != null)
{
    var sourceFileName = Path.GetFileName(sourceFile);
    var targetFileName = Path.Combine(targetDirectory, sourceFileName);
    File.Copy(sourceFileName, targetFileName);
    File.Delete(sourceFileName);
}

Note: instead of copy and delete you can use single Move operation.

If you want to move several files from your source directory, then instead of taking first one process all found files in a loop:

 foreach(var sourceFile in Directory.EnumerateFiles(sourceDirectory, "*.xls"))
 {
     var sourceFileName = Path.GetFileName(sourceFile);
     var targetFileName = Path.Combine(targetDirectory, sourceFileName);
     File.Move(sourceFileName, targetFileName);
 }

Upvotes: 4

Related Questions