简体   繁体   中英

How to move a file from a default directory to another?

It sounds simple but it is not. I am trying to move a file that i made it like this:

string newFileName = string.Format("{0}-{1}-{2}-t{3:00}-{4:00}.txt", 2013, 10, 5, 05, 06);

It is going to look like: 2013-10-5-05-06.txt , from the default directory ( ..\\bin\\debug\\2013-10-5-05-06.txt ) to another directory ( c:\\Users\\Public\\Folder ). I want to keep the name of the file so that other files having almost the same name (small difference between) being moved to the same folder. I tried several methods ( Path.Combine(), string.Concat().. ) without success.

Just use this snippet

string CurrentFileNameAndPath; //the path the file you want to move
string newPath; //only the new the folderPath
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name; //remember that using fullname will get the folder and filename
FileYouWantToMove.MoveTo(NewFileNameAndPath);

So lets use this as an example i have this file C:/Dir1/file1.txt and I want to change its directory to C:/Dir2/ right? then it will be like this

string CurrentFileNameAndPath = @"C:/Dir1/file1.txt";
string newPath = @"C:/Dir2/";
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name;
FileYouWantToMove.MoveTo(NewFileNameAndPath);

the result will the that file in C:/Dir1/file1.txt will be now in C:/Dir2/file1.txt it have been moved and maintened the same file name and extension

Something like this is actually pretty trivial

var srcFile = "..\bin\debug\2013-10-5-05-06.txt";
var destFolder = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
var destFile = Path.Combine(destFolder, Path.GetFileName(srcFile));
File.Move(srcFile, destFile);

Just keep in mind that Move can throw various exceptions eg IOException / UnauthorizedAccessException etc. so it would be wise to handle these where appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM