Search code examples
windowsbatch-filecmdfile-association

To associate file extension with specific program


I'm trying to associate specific file extensions with specific programs. For example, when I press Enter on .txt file, it should be opened in Sublime Text. Or may be in Vim. Or may be in Chrome.

I need to achieve it with command line. At first glance, it could be achieved in the following way:

FTYPE txtfile=C:\Program Files\Google\Chrome\Application\chrome.exe "%1"
ASSOC .txt=txtfile

But actually it does nothing for me: .txt files opens in Sublime Text, not in browser.

What I'm doing wrong?


Solution


  • Try this:

    @echo off && setlocal EnableDelayedExpansion
    
    title <nul && title ...\%~nx0 && cd /d "%~dp0" && mode 50,6 && echo/
    for %%i in (ProgramFiles,ProgramFiles(x86^),ProgramW6432)do if /i defined %%~i (
        for /f tokens^=^* %%z in ('%__APPDIR__%where.exe /r "!%%~i!" "chrome.exe" 2^>nul
        ')do set "_path_chrome=%%~z" && goto :_reg_add_: 
         )
    
    :_reg_add_:
    >nul (
    "%__APPDIR__%reg.exe" add "HKCU\Software\Classes\.txt" /ve /d "txtfile" /f
    "%__APPDIR__%reg.exe" add "HKCU\Software\Classes\txtfile" /ve /d "Text Document" /f
    "%__APPDIR__%reg.exe" add "HKCU\Software\Classes\txtfile\shell\open\command" /ve /d "\"!_path_chrome:\=\\!\" \"file:///%%L\"" /f
    ) 2>nul && endlocal || (endlocal && echo/Something is very wrong here^!!) & %__APPDIR__%timeout.exe -1
    

    Use for loop and get the full path to Chrome.exe, save it to variable and replace \ to \\ for add path value in register...

    Add entries in Windows register with this layout:

    1) Use %%L instead %L

    2) Use \"file:///%%L\" instead \"%L\"

    3) Use "\"!_path_chrome:\=\\!\" instead \"!_path_chrome\"

    Use: \"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"

    Not: \"C:\Program Files\Google\Chrome\Application\chrome.exe\"