[英]Copy file from one directory to another
我對C#相當陌生,我正在嘗試讓我的程序將文件從一個位置復制到另一個位置。 我的方法如下。
private void CopyInstallFiles(object sender, EventArgs e)
{
string sourceFile = "F:\\inetpub\ftproot\test.txt";
string copyPathone = directoryImput.Text;
System.IO.File.Copy(sourceFile, copyPathone);
}
盡可能有一個固定的源位置,但是目標來自用戶輸入(文本框)。 但是,我遇到的問題是,當我嘗試復制到某個位置時,例如C:\\ testfolder。 我收到了非法字符異常。
查看您的sourceFile
字符串,並注意使用\\
,它可以解釋為轉義符 。
為了防止這種情況,請使用@
開頭字符串
string sourceFile = @"F:\inetpub\ftproot\test.txt";
要么
string sourceFile = "F:\\inetpub\\ftproot\\test.txt";
File.Copy需要目標的完整文件名。
destFileName
類型:System.String
目標文件的名稱。 這不能是目錄。
如果您輸入的只是文件夾名稱,則需要添加源文件的文件名。
private void CopyInstallFiles(object sender, EventArgs e)
{
// The correct syntax for a path name requires the verbatim @ char
string sourceFile = @"F:\inetpub\ftproot\test.txt";
string file = Path.GetFileName(sourceFile);
string copyPathone = directoryImput.Text;
System.IO.File.Copy(sourceFile, Path.Combine(copyPathone, file), true);
}
請注意,最后一個參數= true會覆蓋目標文件夾中的文件。
附帶說明,我建議您刪除文本框作為文件夾名稱的輸入,而應使用FolderBrowserDialog
嘗試這個 :
string path = @"C:\Program Files (x86)\your\path\main.txt";
這是因為在C#(以及C ++和C和某些其他語言)中,字符串可以包含特殊字符。 這些字符后跟“ \\”。 因此,例如字符串:
"\n"
不會向您顯示\\ n這是一個特殊字符,稱為-新行。 因此,當您創建這樣的路徑時:
"C:\Dir\file.txt"
C#期望有兩個特殊字符:\\ D和\\ f。 但是沒有像這樣的特殊字符。 因此錯誤。
要將字符“ \\”放入字符串,必須將其加倍,因此:
"\\n"
將輸出\\ n
路徑也一樣:“ C:\\ Dir \\ file.txt”
C#有另一種選擇。 您可以在路徑中使用單個'\\',但是這樣的字符串必須在符號(@)后跟:
string properPath = @"C:\dir\file.txt";
string properPath2 = "C:\\dir\\file.txt";
string error = "C:\dir\file.txt"
可以將文件FIle.Copy
到如下所示的新位置
new_file_path = file_path.Replace(".xls", " created on " + File.GetLastWriteTime(file_path).ToString("dd-MM-yyyy hh-mm-ss tt") + ".xls");
File.Move(file_path, new_file_path);
File.Delete(file_path);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.