1

In my application I could have three paths

  1. \Shared\1.txt
  2. \Shared\
  3. \Shared\*.txt

This file paths will come in variable.

Now How can I check if path has single file or multiple or it has wildcard ? & then move them to another path.

vaibhav shah
  • 4,939
  • 19
  • 58
  • 96
  • 2
    Something like `Directory.GetFiles(@"C:\Shared\", "*.txt").ForEach(file => File.Move(file, Path.Combine(@"C:\Destination", Path.GetFileName(file))));` – Dmitry Bychenko Apr 29 '15 at 06:49
  • To check for a widcard: `Boolean isWildCard = path.ContainsAny('?', '*');` since neither `?` nor `*` can be used within path. – Dmitry Bychenko Apr 29 '15 at 06:54
  • You might want to check this out: http://stackoverflow.com/questions/1395205/better-way-to-check-if-path-is-a-file-or-a-directory – Philip Pittle Apr 29 '15 at 07:18

1 Answers1

2

Well, since neither * nor ? can be in the path: they are in

  Char[] forbidden = Path.GetInvalidPathChars();

so you can just look for them

  String path = @"C:\MyData\Shared\*.txt";
  ...
  Boolean isWildCard = path.ContainsAny('?', '*');

As for File/Directory

  Boolean isFile;

  if (File.Exists(path)) 
    isFile = true; // file already exists
  else if (Directory.Exists(path)) 
    isFile = false; // directory already exists
  else if (String.Equals(Path.GetExtension(path), ".txt", StringComparison.InvariantCultureIgnoreCase))
    isFile = true; // has txt extension, let it be a file
  else
    isFile = false;

However it seems that you have no need to have any branches (isWildCard, isFile) and just move files:

  String path = @"C:\MyData\Shared\*.txt";
  ...
  String sourceDirectory = Path.GetDirectoryName(path);  
  String destination = @"C:\Destination";

  Directory.GetFiles(sourceDirectory, "*.txt")
           .ForEach(file => File.Move(file, Path.Combine(destination, Path.GetFileName(file))));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215