将文件复制到不同的文件夹目录名称

时间:2014-04-22 13:22:40

标签: c#

我已经为复制创建了代码,但如果文件名不在jpegbmppng或{{1},我就不知道如何合并复制代码它将复制到不同的文件夹名称(gif),但如果存在文件扩展名,则文件将被复制到(C:\Dump)。

C:\Destionation

2 个答案:

答案 0 :(得分:1)

您可以将文件的扩展名与:

进行比较
  

Path.GetExtension(myFilePath);

例如,您可以添加代码:

foreach (string file in files)
    {
        string name = Path.GetFileName( file );
        string dest = Path.Combine( destFolder, name );
        if(Path.GetExtension(myFilePath) != "jpg" && Path.GetExtension(myFilePath) !=  "bmp" && Path.GetExtension(myFilePath) !=  "png" && Path.GetExtension(myFilePath) !=  "gif" && Path.GetExtension(myFilePath) !=  "jpeg"      ){
        File.Copy( file, dest);
        }
    }

您可以在Path.GetExtension Method documentation中找到参考。

答案 1 :(得分:1)

FileInfo有一个属性来获取文件Extension

您可以枚举所有文件并复制,具体取决于Extension

public static void Main(string[] args)
{
    var extensions = new[] { "jpg", "jpeg", "bmp", "png", "gif" };
    var source = @"C:\Source";
    var destination = @"C:\Destination";
    var dump = @"C:\Dump";

    CopyFolder(source, destination, dump, extensions);

    Console.ReadLine();
}

public static void CopyFolder(
    string source,
    string destination,
    string dump,
    string[] extensionsForDestination
)
{
    if (!Directory.Exists(destination))
    {
        Directory.CreateDirectory(destination);
    }

    if (!Directory.Exists(dump))
    {
        Directory.CreateDirectory(dump);
    }

    var directory = new DirectoryInfo(source);
    ProcessDirectory(directory, destination, dump, extensionsForDestination);
}

public static void ProcessDirectory(
    DirectoryInfo directory,
    string destination,
    string dump,
    string[] extensionsForDestination
)
{
    foreach (FileInfo file in directory.EnumerateFiles())
    {
        // Check if extension matches
        if(extensionsForDestination.Contains(file.Extension))
        {
            // Copy file to Destination
            file.CopyTo(destination);
        }
        else
        {
            // Copy file to Dump
            file.CopyTo(dump);
        }
    }
}