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

标签 c# file

我正在编写一个 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));
    }
}

现在我收到错误

the file is being used by another program

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

File.Copy(dlg.FileName, destFile);

我收到错误

file already exists

在从中选择它的目录中。

最佳答案

看来您要写入的路径不正确

 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 是否存在,则必须创建它:

 Directory.CreateDirectory(Path.GetDirectoryName(destFile));

关于c# - 无法将文件从一个目录复制到应用程序文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56443051/

相关文章:

c# - 注入(inject)依赖困境的工厂模式和生命周期

c# - ImageButton 中的回发或回调参数无效

c# - 将 System.Drawing.Color 转换为 RGB 和十六进制值

c# - 对包含坐标 x 和 y 的 List<String> 进行排序

Java 打印方 block (未知字符)和常规文本

java - servlet/rest Controller 下载 log4j 日志文件内容没有完全结束

c# - 如何确保 Windows 服务计时器生成的线程在停止 Windows 服务后完成执行?

Java 将 Jar URL 转换为文件

python - 如何使用 python 重命名多个文件?

python - 使用 Python 编写简单的 DMS Web 服务