How can I URL-encode spaces in an NT batch file?
batch-file
Solution
Side note - I believe you want `%~f1` instead of `%~dp1`
You need to switch over to delayed expansion.
@echo off
setlocal enableDelayedExpansion
set "URLPATH=file:/%~f1"
set "URLPATH=!URLPATH:\=/!"
set "URLPATH=!URLPATH: =%%20!"
stupidapp.exe !URLPATH!
endlocal
A bit more work is required if any of your file names happen to contain the `!` character because it will be corrupted when %1 is expanded if delayed expansion is enabled.
@echo off
setlocal disableDelayedExpansion
set "URLPATH=file:/%~f1"
setlocal enableDelayedExpansion
set "URLPATH=!URLPATH:\=/!"
set "URLPATH=!URLPATH: =%%20!"
stupidapp.exe !URLPATH!
endlocal
endlocal
Problem
I have the misfortune of working with a program which requires all filenames passed into it to be valid URLs. (No, I don't know why.) Rather than having to drop to the command line and hand-craft `file:` URLs each time, I'm throwing together a batch file onto which I can simply drop files dragged from the Windows GUI. A full, proper URL encoder is beyond my needs or interest (most of the characters the app chokes on aren't valid in Windows filenames, anyway), but the two cases I do need to solve are backslashes and spaces. Backslashes are easily handled by variable replacement syntax (`SET URL=%URL:\=/%`), but spaces are tricky — `%` is special for both URLs and batch files. Neither type of batch escaping I'm familiar with (`^%`, `%%`) allows the variable replacement to behave as desired and I haven't had any success Googling a solution. Can any batch gurus help me out? Here's what I have so far: ``` @ECHO OFF SETLOCAL SET URLPATH=file:/%~dp1 SET URLPATH=%URLPATH:\=/% REM none of these work REM SET URLPATH=%URLPATH: =%20% REM SET URLPATH=%URLPATH: =%%20% REM SET URLPATH=%URLPATH: =^%20% REM works; I just need to figure out how to generate it SET URLPATH=file:/C:/Documents%%20and%%20Settings/bblank/example.dat stupidapp.exe %URLPATH% ENDLOCAL ```