vb.net 复制具有特定扩展名的所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15303411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:41:06  来源:igfitidea点击:

copy all files with certain extension

vb.netfile

提问by joetinger

Hello I want to copy all files with and a specific extension. I've tried a few things but it isn't working. During my debug I get an exception "Illegal characters used in path" I'm guessing it doesn't like *.xls any suggestions?

您好,我想复制带有特定扩展名的所有文件。我已经尝试了一些东西,但它不起作用。在调试期间,我收到一个异常“路径中使用了非法字符”,我猜它不喜欢 *.xls 有什么建议吗?

First try

第一次尝试

 My.Computer.FileSystem.CopyFile("C:\test\test\mxw\*.xls\", "C:\workorder1-23\workorder1-23\mxw\", True)

second try

第二次尝试

For Each f In Directory.GetFiles("C:\test\test\mxw\*.xls\", CStr(SearchOption.AllDirectories))
     If My.Computer.FileSystem.FileExists(f.ToString) Then
          File.Copy("C:\test\test\mxw\*.xls\", "C:\workorder1-23\workorder1-23\mxw\", True)
     End If
Next

回答by Steve

CopyFile copies just one file.
You cannot use it with wildcards to copy a group of files. (The invalid character is probably the wildcard) And you should not append a backslash at the end of the file.

CopyFile 只复制一个文件。
您不能将它与通配符一起使用来复制一组文件。(无效字符可能是通配符)并且您不应在文件末尾附加反斜杠。

So let me try to replace your code with this

所以让我试着用这个替换你的代码

For Each f In Directory.GetFiles("C:\test\test\mxw", "*.xls", SearchOption.AllDirectories)
     If File.Exists(f) Then
          File.Copy(f, Path.Combine("C:\workorder1-23\workorder1-23\mxw", Path.GetFileName(f)), True)
     End If
Next

Also Directory.GetFileshas three parameters, a path, a pattern and a flag to read subfolders

Directory.GetFiles有三个参数,路径,图案和标记读取的子文件夹

回答by AfterMidnight

Since File.Copy does not create directories the provided answer will only work if the target directories exist. Add a Create.Directory(f) before the File.Copy if they don't.

由于 File.Copy 不创建目录,因此提供的答案仅在目标目录存在时才有效。如果没有,则在 File.Copy 之前添加 Create.Directory(f)。