压缩重复的if语句

时间:2013-03-18 19:18:15

标签: c# if-statement repeat

我有以下代码,它扫描目录并将包含“a”的文件放在其文件名中。同样,它将文件名中带有“b”的文件放到名为B的新文件夹中。如果语句基本相同,唯一的变化是字母“a”或“b”并被发送到destA或destb(desitinations),我该如何修改这些代码呢?我知道有更好的方法,因为大部分代码都会重复...谢谢。

static void Main()
{
    string path = @"C:\Users\me\Desktop\FOLDER";
    string destA = @"C:\Users\me\Desktop\FOLDER\A";
    string destB = @"C:\Users\me\Desktop\FOLDER\B";

    DirectoryInfo dir = new DirectoryInfo(path);
    FileInfo[] filesxx = dir.GetFiles();
    foreach (FileInfo filexx in filesxx)
    {
        if (filexx.Name.Contains("a"))
        {
            if (!Directory.Exists(destA))
                Directory.CreateDirectory(destA);
            Console.WriteLine(filexx);
            filexx.CopyTo(Path.Combine(destA, filexx.Name), true);
        }
        else if (filexx.Name.Contains("b"))
        {
            if (!Directory.Exists(destB))
                Directory.CreateDirectory(destB);
            Console.WriteLine(filexx);
            filexx.CopyTo(Path.Combine(destB, filexx.Name), true);
        } 
        else
        {
            Console.WriteLine("Other: ", filexx);
        }
    }
    Console.Read();
}

2 个答案:

答案 0 :(得分:0)

创建一个方法,如:

private Boolean MoveFile(FileInfo filexx, String nameMatch, String destDirectory) {
  Boolean result = false;
  if (filexx.Name.Contains(nameMatch)) {
    if (!Directory.Exists(destDirectory)) {
      Directory.CreateDirectory(destDirectory);
    }
    Console.WriteLine(filexx);
    filexx.CopyTo(Path.Combine(destDirecotry, filexx.Name), true);
    result = true;
  }
  return result;
}

然后根据需要调用它。

foreach(FileInfo filexx in filesxx) {
  if (!MoveFile(filexx, "a", destA)) {
    if (!MoveFile(filexx, "b", destB)) {
      Console.WriteLine("Other: ", filexx);
    }
  }
}

当然,这里有一个潜在的优先问题。如果文件名为“abcd”怎么办?它应该转到A文件夹还是B文件夹?

答案 1 :(得分:0)

如果你所寻找的只是更少的代码,那就应该这样做。

   public static void Main()
        {
            const string TargetPath = @"C:\Users\me\Desktop\FOLDER";
            var dir = new DirectoryInfo(TargetPath);
            var files = dir.GetFiles();
            foreach (var file in files.Where(file => !CopyFile(TargetPath, file, "a")).Where(file => !CopyFile(TargetPath, file, "b")))
            {
                Console.WriteLine("Other: " + file.Name);
            }

            Console.Read();
        }

        private static bool CopyFile(string dir, FileInfo file, string match)
        {
            if (!file.Name.Contains(match))
            {
                return false;
            }

            dir = dir + "\\" + match.ToUpper();
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            Console.WriteLine(file);
            file.CopyTo(Path.Combine(dir, file.Name), true);
            return true;
        }