简体   繁体   English

如何在C#中将文件从一个路径移动到另一路径

[英]How to move files from one path to another in c#

In my application I could have three paths 在我的应用程序中,我可以有三个路径

  1. \\Shared\\1.txt \\共享\\的1.txt
  2. \\Shared\\ \\共享\\
  3. \\Shared\\*.txt \\共享\\ *。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. 然后将它们移到另一条路径。

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: 但是,似乎您不需要任何分支(isWildCard,isFile),只需移动文件即可:

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

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

相关问题 尝试使用子文件夹C#将文件从一个文件夹移动到另一个文件夹 - Trying to move files from one folder to another with subfolders C# 如何在C#中将所选项目从一个列表视图移动到另一个列表视图? - How to move selected item from one listview to another in C#? 如何将数据从一个表移动到另一个C# - how to Move data from one table to another c# 将文件从一个文件夹移动到另一进程正在使用的C#错误文件 - Move files from one folder to another C# Error File being used by another process 如何在C#中将所选项目从一个C1List移动​​到另一个? - How to move move selected items from one C1List to another in C#? 如何将文件从一个ftp移动到另一个 - how to move files from one ftp to another C# 将文件从一个目录移动到另一个目录 Azure 文件共享 - C# Move files from one directory to another on Azure File share 如何使用C#从一个路径复制文件夹并将其粘贴到另一路径? - How to copy a folder from one one path and paste it to another path using C#? 将所有pdf文件从一个路径复制到另一路径,而在c#中没有循环 - Copy all pdf files from one path to another without loop in c# 如何将一个文件从一个路径保存到另一路径? 无需使用C#从原始路径中删除文件 - How to save one file from one path to another path? Without removing file from original path using C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM