Bradley
Bradley

Reputation: 617

Moving a file in c# without renaming it

I have a collection of XML files I am looping through and moving the files that have errors to another file location. However when I'm using the system.io.file.move function it requires me to specify a file name instead of moving the file path. Is there a way I can move the file from one location to another while keeping the same name? I am currently creating a name based on the position of the file in the array which isn't really feasible.

string ErrorPath = string.Format(@"{1}ErroredXml{0}.xml", errorLength, errorPaths);

//If type equals "add" then call add method else call update
if (Equals(type, typecomp))
{
    //pass object to data access layer to add record
    value.addNewGamePlay();

    if (value.getGamePlayID() == 0)
    {
        //move to error file
        System.IO.File.Move(value.getFile(), ErrorPath);
        errorLength++;
    }
}

Upvotes: 1

Views: 3210

Answers (2)

CRDave
CRDave

Reputation: 9285

Move method does not require to change name of file. the second argument is not a new name to file but a new path to file for example

first argument (sourceFileName) @"c:\temp\MyTest.txt"

second argument (destFileName) @"c:\temp2\MyTest.txt"

so file name is same "MyTest.txt" just position is changed.

Upvotes: -1

Jon
Jon

Reputation: 437336

You can use Path.GetFileName to extract the original file name and construct the destination path with it using Path.Combine:

var original = value.getFile();
var destinationPath = Path.Combine(errorPaths, Path.GetFileName(original));

Upvotes: 8

Related Questions