2014-12-06 124 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

相關問題