Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将文件从一个目录复制到应用程序文件夹_C#_File - Fatal编程技术网

C# 无法将文件从一个目录复制到应用程序文件夹

C# 无法将文件从一个目录复制到应用程序文件夹,c#,file,C#,File,我正在编写一个c桌面应用程序,希望用户从“打开文件”对话框中选择一个文件,然后程序会将文件复制到应用程序执行的位置:这是我目前无法运行的代码 var dlg = new Microsoft.Win32.OpenFileDialog { Title = "Select File", DefaultExt = ".json", Filter = "Json File (.json)|*.json", CheckF

我正在编写一个c桌面应用程序,希望用户从“打开文件”对话框中选择一个文件,然后程序会将文件复制到应用程序执行的位置:这是我目前无法运行的代码

var dlg = new Microsoft.Win32.OpenFileDialog { 
    Title           = "Select File", 
    DefaultExt      = ".json", 
    Filter          = "Json File (.json)|*.json", 
    CheckFileExists = true 
};

if (dlg.ShowDialog() == true)
{
    try
    {
        var currentDirectory = System.Windows.Forms.Application.ExecutablePath;
        var destFile = Path.Combine(currentDirectory + "/temp/", dlg.FileName);

        File.Copy(dlg.FileName, destFile, true);
    }
    catch (Exception ex)
    {
        MessageBox.Show(string.Format("An error occured: " + ex.Message));
    }
}
现在我得到的错误是

另一个程序正在使用该文件

。当我编辑要通过删除true来启动复制的代码时:

File.Copy(dlg.FileName, destFile);
我得到的错误是

文件已存在


在选择它的目录中。

似乎您有一个不正确的写入路径

 System.Windows.Forms.Application.ExecutablePath
返回exe文件本身,而不是目录。试一试

 var destFile = Path.Combine(
   Path.GetDirectoryName(Application.ExecutablePath), // Exe directory
  "temp",                                             // + Temp subdirectory
   Path.GetFileName(dlg.FileName));                   // dlg.FileName (without directory)
如果不确定temp是否存在,则必须创建它:


使用以下代码将文件从一个文件夹复制到另一个文件夹

string[] filePaths = Directory.GetFiles("Your Path");
    foreach (var filename in filePaths)
    {
        string file = filename.ToString();

        //Do your job with "file"

        string str = "Your Destination"+file.ToString(),Replace("Your Path");
        if (!File.Exists(str))
        {
            File.Copy(file , str);
        }
    }
键入File.Copy时,我只看到两个参数filename和destfilenamevar destFile=Path.CombinePath.GetDirectoryNamecurrentDirectory,temp,Path.GetFileNamedlg.filename;
string[] filePaths = Directory.GetFiles("Your Path");
    foreach (var filename in filePaths)
    {
        string file = filename.ToString();

        //Do your job with "file"

        string str = "Your Destination"+file.ToString(),Replace("Your Path");
        if (!File.Exists(str))
        {
            File.Copy(file , str);
        }
    }