我有一個包含檔案夾和檔案的目錄,我想將所有檔案夾移動到目錄內的另一個檔案夾中。
我已經可以移動目錄中的所有檔案(不包括子檔案夾中的檔案),但我也在試圖弄清楚如何移動子檔案夾。
string selectedDrive = comboBox1.SelectedItem.ToString();
string folderName = selectedDrive @"\\Encrypted"; // Creates a directory under the selected drive.
System.IO.Directory.CreateDirectory(folderName);
string moveTo = (selectedDrive @"\Encrypted");
String [] allFolders = Directory.GetDirectories(selectedDrive); //Should return folder
foreach (String Folder in allFolders)
{
if (!Directory.Exists(moveTo Folder))
{
FileSystem.CopyDirectory(Folder, moveTo);
}
}
相反,我在這一行有一個錯誤,FileSystem.CopyDirectory(Folder, moveTo);
內容如下:System.IO.IOException: 'Could not complete operation since source directory and target directory are the same.'
uj5u.com熱心網友回復:
我已經修改了您的代碼以使其以這種方式作業:
// source of copies, but notice the endslash, it's required
// if you use the string replace method below
string selectedDrive = @"E:\temp\";
string destFolderName = Path.Combine(selectedDrive, "Encrypted");
System.IO.Directory.CreateDirectory(destFolderName);
// All folders except the one just created
var allFolders = Directory.EnumerateDirectories(selectedDrive)
.Except(new[] { destFolderName });
// Loop over the sources
foreach (string source in allFolders)
{
// this line in framework 4.8,
string relative = source.Replace(selectedDrive, "");
// or this line if using NET Core 6
// string relative = Path.GetRelativePath(selectedDrive, source));
// Create the full destination name
string dest = Path.Combine(destFolderName, relative);
if (!Directory.Exists(dest))
{
FileSystem.CopyDirectory(source, dest);
}
}
現在還要注意,您正在使用根驅動器 (F:) 作為要復制的目錄的源。在這種情況下,您應該考慮您有其他檔案夾不可訪問或不可復制。(例如 Recycle.bin 檔案夾)。但是,您可以輕松地將其他排除項添加到傳遞給 IEnumerable 擴展的陣列中Except
....
.Except(new[] { destFolderName, "Recycle.bin" });
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/524201.html
標籤:C#。网文件目录子目录
上一篇:加減法最多的專案的索引
