将Windows驱动器号解析为路径(subst和network)

时间:2009-08-19 13:05:45

标签: winapi networking resolve drive-letter subst

我想知道是否存在一种使用驱动器号(例如X:\foo\bar.txt)将路径解析为等效UNC路径的通用方法,该路径可能是以下之一:

  • X:\foo\bar.txt如果X:是真正的驱动器(即硬盘,USB记忆棒等)
  • \\server\share\foo\bar.txt如果X:\\server\share
  • 上安装的网络驱动器
  • C:\xyz\foo\bar.txt如果X:SUBST命令映射X:C:\xyz
  • 的结果

我知道有部分解决方案可以:

  1. 解析网络驱动器(请参阅question 556649依赖WNetGetUniversalName

  2. 解析SUBST驱动器号(请参阅QueryDosDevice,其工作正常,但不会返回本地驱动器或网络驱动器等UNC路径。

  3. 我是否错过了在Win32中实现此驱动器号解析的一些简单方法?或者我是否真的不得不同时使用WNetGetUniversalNameQueryDosDevice以获得我需要的东西?

2 个答案:

答案 0 :(得分:6)

这是一个将驱动器号转换为UNC路径或反向子路径的批处理。不保证它有效。

使用示例:script.cmd echo Z: Y: W:

@echo off
:: u is a variable containing all arguments of the current command line
set u=%*

:: enabledelayedexpansion: exclamation marks behave like percentage signs and enable
:: setting variables inside a loop
setlocal enabledelayedexpansion

:: parsing result of command subst
:: format:  I: => C:\foo\bar
:: variable %G will contain I: and variable H will contain C:\foo\bar
for /f "tokens=1* delims==> " %%G IN ('subst') do (
set drive=%%G
:: removing extra space
set drive=!drive:~0,2!
:: expanding H to a short path in order not to break the resulting command line
set subst=%%~sfH
:: replacing command line.
call set u=%%u:!drive!=!subst!%%
)

:: parsing result of command net use | findstr \\ ; this command is not easily tokenized because not always well-formatted
:: testing whether token 2 is a drive letter or a network path.
for /f "tokens=1,2,3 delims= " %%G IN ('net use ^| findstr \\') do (
set tok2=%%H
if "!tok2:~0,2!" == "\\" (
  set drive=%%G
  set subst=%%H
) else (
  set drive=%%H
  set subst=%%I
)
:: replacing command line.
call set u=%%u:!drive!=!subst!%%
)

call !u!

答案 1 :(得分:2)

是的,您需要单独解决驱动器号。

WNetGetUniversalName()接近,但仅适用于映射到实际UNC共享的驱动器号,但情况并非总是如此。没有单一的API函数能够为您完成所有工作。

相关问题