繁体   English   中英

如何将数组中的所有文件路径移动到一个目录

[英]How do I move all the file paths in an array to one directory

这是我尝试过的

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);
    }
}

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

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

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM