【问题标题】:How do I move all the file paths in an array to one directory如何将数组中的所有文件路径移动到一个目录
【发布时间】:2021-08-19 09:20:48
【问题描述】:

这是我尝试过的

string[] filestomove = new string[] {"text.txt", "never.json", "gonna.dll", "giveyou.exe", "up.png"};
string[] dirstomove = new string[] {"never gonna", "let you down", "never gonna", "run around", "and desert you"};
foreach(string filename in filestomove)
{
    if(File.Exists(filename)) {
        File.Copy(filename, path, true);
    }
}

foreach(string dirname in dirstomove)
{
    if(Directory.Exists(dirname)) {
        Directory.Move(dirname, path);
    }
}

但是,由于某种原因,它对我不起作用,它给了我一个错误。有谁知道怎么做?

【问题讨论】:

  • 你得到了什么“错误”?
  • 从技术上讲,您的代码不会尝试移动文件路径而是文件名(您的 filestomove 数组没有路径)
  • 你刚刚rickroll SO?喜欢文件名和目录名
  • @Markus 可能是StrangersToLoveException ????。 OP:您是否试图将嵌套目录的内容扁平化到单个目录中?如果是这样,您打算如何处理文件名冲突(例如 c:\folder\subfolder\A.txtc:\folder\subfolder2\A.txt 移动到 c:\flatfolder\A.txt
  • @Martin 没想到会从 StackOverflow 成为 RickRolled

标签: c# file system.io.file system.io.directory


【解决方案1】:

您需要指定要写入的完整路径:

string[] filestomove = new string[] {"text.txt", "never.json", "gonna.dll", "giveyou.exe", "up.png"};
string[] dirstomove = new string[] {"never gonna", "let you down", "never gonna", "run around", "and desert you"};
foreach(string filename in filestomove)
{
    if(File.Exists(filename)) 
    {
        // from c:\folder\A.txt, extract A.txt
        string name = Path.GetFileName(filename);

        // combine that with path to get c:\newfolder\A.txt
        string targetFileName = Path.Combine(path, name);
     
        // Move the file
        File.Copy(filename, targetFileName, true);
    }
}

foreach(string dirname in dirstomove)
{
    if(Directory.Exists(dirname)) 
    {
        // From c:\folder\somefolder get somefolder
        string name = new DirectoryInfo(dirname).Name;
        
        // Combine that with path to get c:\newfolder\somefolder
        string targetDirectory = Path.Combine(path, name);

        // Move the directory
        Directory.Move(dirname, targetDirectory);
    }
}

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多