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