将文件从一个目录复制到另一个目录 [英] Copy file from one directory to another

查看:177
本文介绍了将文件从一个目录复制到另一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#来说还很陌生,我正在尝试让我的程序将文件从一个位置复制到另一个位置。我的方法如下;

  private void CopyInstallFiles(object sender,EventArgs e)
{
字符串sourceFile = F:\\inetpub\ftproot\test.txt;
string copyPathone = directoryImput.Text;
System.IO.File.Copy(sourceFile,copyPathone);
}

您可以找到一个固定的来源位置,但是目的地是从用户输入(文本框)。但是,我遇到的问题是,当我尝试复制到某个位置时,例如C:\testfolder。我收到了非法字符异常。

解决方案

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


destFileName

类型:System.String

目标文件的名称。这不能是目录。


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

  private void CopyInstallFiles(object sender,EventArgs e)
{
// a的正确语法路径名需要逐字@ char
字符串sourceFile = @ F:\inetpub\ftproot\test.txt;
字符串文件= Path.GetFileName(sourceFile);
string copyPathone = directoryImput.Text;
System.IO.File.Copy(sourceFile,Path.Combine(copyPathone,file),true);
}

请注意,最后一个参数= true会覆盖目标文件夹中的文件。 / p>

作为旁注,我建议您删除文本框作为文件夹名称的输入,而应使用文件夹浏览器对话框


I am pretty new to C# and I am trying to get my program to copy a file from one location to another. The method I have is as below;

    private void CopyInstallFiles(object sender, EventArgs e)
    {
        string sourceFile = "F:\\inetpub\ftproot\test.txt";
        string copyPathone = directoryImput.Text;
        System.IO.File.Copy(sourceFile, copyPathone);
    }

As you can is there is a fixed source location however the destination is taken from user input (text box). The problem I have however, is that when I try to copy to a location for example C:\testfolder. I get an illegal character exception.

解决方案

File.Copy requires the full filename for the destination.

destFileName
Type: System.String
The name of the destination file. This cannot be a directory.

If your input is just the folder name then you need to add the filename of the source file.

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

Note the final parameter = true to overwrite a file in the destination folder.

As a side note, I suggest you to remove the textbox as input for a folder name but instead use the FolderBrowserDialog

这篇关于将文件从一个目录复制到另一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆