長い形式のファイル名取得(VB)

キーワード:

FindFirstFile, FindClose

サンプルコード:

Private Sub GetLongPathName()

	Dim hFind As Long
	Dim FindData As WIN32_FIND_DATA
	Dim ShortFileName As String
	Dim Idx As Integer
	Dim NextDelim As Integer
	Dim InsSep As String
	Dim LongFileName As String
	Dim Token As String

	ShortFileName = "c:\MYDOCU~1\012345~1\ABCDEF~1.TXT" 'can't root dir
	Idx = 1

	ShortFileName = Trim(ShortFileName)
	If Left(ShortFileName, 1) <> "\" Then
		ShortFileName = ShortFileName + "\" '番人
	End If

	If Left(ShortFileName, 2) = "\\" Then
		Idx = Idx + 2
		If Mid(ShortFileName, Idx, 1) = "?" Then
			MsgBox "error"
			Exit Sub
		End If

		Idx = InStr(Idx, ShortFileName, "\") + 1
	End If

	    
	If Mid(ShortFileName, Idx + 1, 1) = ":" Then Idx = Idx + 2
	If Mid(ShortFileName, Idx, 1) = "\" Then Idx = Idx + 1

	LongFileName = Left(ShortFileName, Idx - 1)

	NextDelim = InStr(Idx, ShortFileName, "\")

	Do
		Token = Mid(ShortFileName, Idx, NextDelim - Idx + 1)
		If Token = ".\" Or Token = "..\" Then
			FindData.FileName = Left(Token, Len(Token) - 1)
		Else
			hFind = FindFirstFile(Left(ShortFileName, NextDelim - 1), FindData)
			If hFind = INVALID_HANDLE_VALUE Then
				MsgBox "error"
				Exit Sub
			End If

			FindClose hFind

			With FindData
				.FileName = Left(.FileName, InStr(.FileName, vbNullChar) - 1)
			End With
		End If

		LongFileName = LongFileName & InsSep & Trim(FindData.FileName)

		InsSep = "\"

		Idx = NextDelim + 1
		NextDelim = InStr(NextDelim + 1, ShortFileName, "\")
	Loop Until NextDelim = 0

	MsgBox LongFileName

End Sub


(original text:1998/12/25 更新)

本ドキュメントの内容は保証しません。本ドキュメントによって生じた結果について、一切の責任を負いません。