我在将文件从列表框移动到新创建的文件夹时遇到问题。我得到:该文件已存在时无法创建文件。
public void CreateFolders()
{
//create folders
string folder1 = pattern.Substring(0, 2);
string folder2 = pattern.Substring(3, 2);
string folder3 = pattern.Substring(6, 2);
Directory.CreateDirectory("c:\\destinationfolder" + "\\" + folder1);
Directory.CreateDirectory("c:\\destinationfolder" + "\\" + folder1 + "\\" + folder2);
Directory.CreateDirectory("c:\\destinationfolder" + "\\" + folder1 + "\\" + folder2 + "\\" + folder3);
var destinationDirectoryFinal = Directory.CreateDirectory("c:\\destinationfolder" + "\\" + folder1 + "\\" + folder2 + "\\" + folder3);
destinationDirectory = destinationDirectoryFinal.FullName.ToString();
}
public void MoveFiles()
{
try
{
//Move files from listbox to newly created folders
foreach (string files in listBox1.Items)
{
File.Move(files, destinationDirectory);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
答案 0 :(得分:1)
这里遇到的问题是,您试图将文件移动到已经包含该名称文件的目录中。
您可以选择以下两个选项:
在尝试Move
之前检查文件是否存在
foreach (var file in listBox1.Items)
{
// Only move the file if it doesn't already exist
if (!File.Exists(Path.Combine(destinationDirectory, Path.GetFileName(file))))
{
File.Move(file, destinationDirectory);
}
}
始终覆盖文件(如果存在)。我们可以分两步进行操作-首先通过将“ overwrite”参数设置为File.Copy
来调用true
,然后通过调用File.Delete
来删除原始位置的文件:
foreach (var file in listBox1.Items)
{
// If the destination file already exists, overwrite it. Then delete the original
File.Copy(file, Path.Combine(destinationDirectory, Path.GetFileName(file)), true);
File.Delete(file);
}
注意: 防止错误(无论哪种情况)的另一件事是,在尝试尝试任何操作之前,请确保源文件存在,并且源目录与目标目录不同:
foreach (var file in listBox1.Items)
{
// Ensure that the file exists and that the source
// and destination directories are not the same
if (!(File.Exists(file)) ||
Path.GetDirectoryName(file).Equals(
destinationDirectory, StringComparison.OrdinalIgnoreCase))
{
continue; // Continue to the next loop iteration without doing anything
}
// Rest of loop code here...
}