For Each File In Folder.Files
只要文件名(包括路径(的长度在Windows的259个字符的限制范围内就可以正常工作。但是,如果文件名(包括路径(较长,那么它就不起作用。
这里有一个例子:
ShortPath = "C:TEST"
LongPath = "C:TESTLONG"
Set FSO = CreateObject("Scripting.FileSystemObject")
Call FSO.CreateFolder(ShortPath)
Call FSO.CreateTextFile(ShortPath & "" & String(240, "A"), True)
Call FSO.CreateTextFile(ShortPath & "" & String(250, "B"), True)
Call FSO.MoveFolder(ShortPath, LongPath)
Set Folder = FSO.GetFolder(LongPath)
For Each File In Folder.Files
Msgbox("File: " & File.Name & vbCrLf & "Length: " & Len(LongPath & "" & File.Name))
Next
通过重命名文件夹";C: "测试";至";C: \TESTLONG";,文件名的长度";啊"(包括路径(为252(12+240(个字符,仍然少于260个字符。因此列出了此文件
但是文件名的长度"BBB"(包括路径(现在是262(12+250(个字符,超过259个字符,这意味着它没有列出。
是否有办法识别过长的文件名(包括路径(
备注:我想检查一个目录及其所有子目录中每个文件的长度(包括路径(。
方法1:使用NT对象路径样式的路径:
请参阅Hans在本QA中的回答:访问具有长路径(超过260(的文件
基本上,更改路径以使用\?
作为前缀:
顺便说一句,我修改了你的代码如下:
- 使用
Option Explicit
- 从函数调用语句中删除
Call
关键字,请注意,在不使用Call
时必须省略括号 - 对局部使用
camelCase
Option Explicit ' ALWAYS use Option Explicit!
Dim shortPath: shortPath = "\?C:TEST"
Dim longPath : longPath = "\?C:TESTLONG"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateFolder shortPath
Dim streamA, streamB
Set streamA = fso.CreateTextFile( shortPath & "" & String(240, "A"), True )
Set streamB = fso.CreateTextFile( shortPath & "" & String(250, "B"), True )
fso.MoveFolder shortPath, longPath
Dim folder
Set folder = fso.GetFolder( longPath )
Dim file
For Each file In folder.Files
Dim msg: msg = "File: " & file.Name & vbCrLf & "Length: " & Len(longPath & "" & File.Name)
Msgbox(msg)
Next
方法2:
将
HKLMSYSTEMCurrentControlSetControlFileSystemLongPathsEnabled
设置为DWORD
1
。添加或编辑
cscript.exe
和wscript.exe
的应用程序清单以添加以下元素:<application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings"> <ws2:longPathAware>true</ws2:longPathAware> </windowsSettings> </application>