gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:21:22 26 4
gpt4 key购买 nike

我正在编写一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com