将文件从一个目录复制到另一个目录

问题描述:

我对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的位置时。我收到一个非法字符的例外。

+1

'\ t '被翻译成制表符(从'F:\\ inetpub \ ftproot \ test.txt') – fubo

File.Copy需要为目标的完整文件名。

destFileName
类型:System
目标文件的名称。这不能是一个目录。

如果您的输入只是文件夹名称,那么您需要添加源文件的文件名。

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

注意final参数= true覆盖目标文件夹中的文件。

作为一个方面说明,我建议你删除文本框中输入一个文件夹名称,而是使用FolderBrowserDialog

看看你的sourceFile字符串,并注意使用\,这可能会被解释为escape character

为了防止这种启动字符串@

string sourceFile = @"F:\inetpub\ftproot\test.txt"; 

string sourceFile = "F:\\inetpub\\ftproot\\test.txt"; 

试试这个:

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:\迪尔\文件.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); 
+0

新的文件路径可以是另一个目录的地址 – Saurabh