Mahmut EFE
Mahmut EFE

Reputation: 5248

Move a file to under a directory using C#

string str = "C:\\efe.txt";
string dir = "D:\\";

I want to move or copy "efe.txt" file under "D:\" directory. How can I do that.

thanks for your advice.....

Upvotes: 4

Views: 6850

Answers (3)

juharr
juharr

Reputation: 32266

As others have mentioned you want to use File.Move, but given your input you'll also want to use Path.Combine and Path.GetFileName like so

string str = "C:\\efe.txt";
string dir = "D:\\";
File.Move(str, Path.Combine(dir, Path.GetFileName(str)));

Upvotes: 8

p.s.w.g
p.s.w.g

Reputation: 148980

Try File.Move

using System.IO;
...
string src = "C:\\efe.txt";
string dest = "D:\\efe.txt";
File.Move(src, dest);

Upvotes: 4

Jared Harley
Jared Harley

Reputation: 8337

From MSDN: How to: Copy, Delete, and Move Files and Folders (C# Programming Guide):

// Simple synchronous file move operations with no user interface. 
public class SimpleFileMove
{
    static void Main()
    {
        string sourceFile = @"C:\Users\Public\public\test.txt";
        string destinationFile = @"C:\Users\Public\private\test.txt";

        // To move a file or folder to a new location:
        System.IO.File.Move(sourceFile, destinationFile);

        // To move an entire directory. To programmatically modify or combine 
        // path strings, use the System.IO.Path class.
        System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
    }
}

Upvotes: 7

Related Questions