2014-12-06 123 views
0

听起来很简单,但事实并非如此。我想移动,我把它像这样的文件:如何将文件从默认目录移动到另一个目录?

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()..),但没有成功。

+0

你的问题似乎更多的是如何创建一个路径,而不是移动文件。 – t3chb0t 2014-12-06 15:44:07

回答

0

只要使用这个片段

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:/方向2 /右?那么它会是这样

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它已经被移动,maintened相同的文件名和延伸

+0

是你的意思:字符串CurrentFileNameAndPath = Path.GetFullPath(newFileName); – Steve 2014-12-06 16:49:01

+0

是的,它应该是currentFullName o您想要更改的文件,如C:/Users/YourName/Desktop/File.txt – Patrick 2014-12-06 16:51:27

+0

FileYouWantToMove是newFileName或2013-10-5-05-06.txt ?.我很困惑。不能:newFileName.Name和newFileName.MoveTo()。 – Steve 2014-12-06 17:41:45

0

这样的事情实际上是非常琐碎

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等,所以这是明智的处理这些适当的地方。

+0

Path.GetDirectoryPath:路径下没有GetDirectoryPath? – Steve 2014-12-06 16:18:31

+0

@Steve这是一个错字,我已经编辑了我的答案。 – James 2014-12-06 16:19:14

+0

它没有工作。我试过字符串srcFile = Path.GetFullPath(newFileName);我用了其余的代码,但没有发生任何事情。我只是得到:文件存在。 – Steve 2014-12-06 16:45:31

相关问题