繁体   English   中英

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

[英]How to move a file from a default directory to another?

听起来很简单,但事实并非如此。 我正在尝试移动这样制作的文件:

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

它看起来像: 2013-10-5-05-06.txt ,从默认目录( ..\\bin\\debug\\2013-10-5-05-06.txt )到另一个目录( c:\\Users\\Public\\Folder )。 我想保留文件名,以便将具有几乎相同名称(彼此之间的差异很小)的其他文件移至同一文件夹。 我尝试了几种方法( Path.Combine(), string.Concat().. )都没有成功。

只需使用此片段

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);

因此,以这个为例,我有这个文件C:/Dir1/file1.txt,我想将其目录更改为C:/ Dir2 /,对吗? 然后会是这样

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);

结果将使C:/Dir1/file1.txt中的文件现在位于C:/Dir2/file1.txt中,该文件已被移动并维护了相同的文件名和扩展名

这样的事情实际上是微不足道的

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);

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

暂无
暂无

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

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