简体   繁体   English

如何将文件从默认目录移动到另一个目录?

[英]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 ). 它看起来像: 2013-10-5-05-06.txt ,从默认目录( ..\\bin\\debug\\2013-10-5-05-06.txt )到另一个目录( 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. 我尝试了几种方法( Path.Combine(), string.Concat().. )都没有成功。

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? 因此,以这个为例,我有这个文件C:/Dir1/file1.txt,我想将其目录更改为C:/ Dir2 /,对吗? 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 结果将使C:/Dir1/file1.txt中的文件现在位于C:/Dir2/file1.txt中,该文件已被移动并维护了相同的文件名和扩展名

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. 请记住, Move可以引发各种异常,例如IOException / UnauthorizedAccessException等。因此,在适当的地方处理这些异常将是明智的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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