首页 > 解决方案 > 文件路径长了255个字符,这个“255”怎么解释?

问题描述

我正在开发一个 Visual Basic 项目,我们在其中开发一个 Word 选项卡。我遇到了一个问题,当用户使用路径超过 255 个字符的 word 文档时,会出现以下错误。

Unexpected error 9105 : String is longer than 255 characters.

我在网上搜索了“255”是如何创建的,发现

Windows 中存在限制,文件/文件夹的最大绝对文件路径长度为 MAX_PATH(定义为 260)。

还发现,

Microsoft Office 文档的完整路径包括驱动器号或服务器名称,以及直到并包括文档名称的所有字符和文件夹名称。整个路径在 Word 中不能超过 242 个字符,在 Excel 中不能超过 218 个字符。

另外我在对这个问题进行测试时发现,当文件路径长度为 254 时,我们也有同样的错误,这是因为不可见的 NUL 终止符。

255 = 254 + 1(NUL 终止符)

谁能解释一下这个“255”是如何创建的?理论是什么?

谢谢你。

标签: windowsms-wordvb6ms-office

解决方案


I can't tell you precisely why the OS designers decided to confine the length to 260 characters, beyond that I'm sure that memory allocation considerations had something to do with it. But I can tell you a trick to shorten path names so that there are only eight characters per directory (otherwise known as 8.3 aliasing). That will allow path names that are 27 levels deep, which should solve most, if not all, of your problems.

If you have this path name:

C:\my long directory\my other long directory name\my long directory again\my long file.txt

the short version would be:

C:\MYLONG~1\MYOTHE~1\MYLONG~2\MYLONG~1.TXT

To get the short path name programmatically (borrowed from here):

Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal longPath As String, ByVal shortPath As String, ByVal shortBufferSize As Long) As Long

'The path you want to convert to its short representation path.
Dim longPathName As String

longPathName = "C:\my long directory\my other long directory name\my long directory again\my long file.txt"

'Get the size of the string to pass to the string buffer.
Dim longPathLength As Long

longPathLength = Len(longPathName)

'A string with a buffer to receive the short path from the api call…
Dim shortPathName As String

shortPathName = Space$(longPathLength)

'Will hold the return value of the api call which should be the length.
Dim returnValue As Long

'Now call the function to do the conversion…
returnValue = GetShortPathName(longPathName, shortPathName, longPathLength)

MsgBox(shortPathName)

You can use the short path name in any context that you would use the usual path name.

Since you're interested in the whys of things, Windows originally replaced MS-DOS, which allowed file names and/or directory names of up to eight characters only, with an optional three-character extension. Windows wanted to support longer file and path names without breaking compatibility with the DOS format, so they came up with this method of abbreviating long file names.

For more information, see Naming Files, Paths and Namespaces.


推荐阅读