临时设置文件关联
问题描述:
我有一个便携式开发工具,我想在其他PC上使用。我想设置一个文件关联,以便点击一个文件打开这个工具。然后,当我完成时,我想撤消或重置该PC上的文件关联。临时设置文件关联
有没有办法做到这一点?可能来自批处理文件?
答
那么,你可以使用ftype
和assoc
命令来创建或删除文件类型关联:
ASSOC .foo=FooFile
FTYPE FooFile=X:\Foo\foo.exe %1 %*
您可以
FTYPE FooFile=
ASSOC .foo=
编辑后删除它们:我有现在尝试一些可以让您将关联重新设置回默认值的东西。我把它放在my Subversion repo。在现阶段它会生成两个新的批处理文件:set.cmd
和reset.cmd
;其中一个设置一个新的关联,另一个反转它。将set.cmd
滚入实际的批次应该不会太困难,但它会使测试成为地狱,所以我会把它作为练习。
代码如下,它应该有足够的评论,希望。
@echo off
setlocal enableextensions enabledelayedexpansion
rem Debug flag. Generates a little more output; un-set if undesired
set DEBUG=1
rem Parse arguments and help
if [%1]==[] goto Usage
if [%2]==[] goto Usage
rem Find out whether the association is taken
for /f "usebackq tokens=2* delims==" %%x in (`assoc .%1 2^>nul`) do set assoc_old=%%x
if defined DEBUG (
if defined assoc_old (echo Association already defined: [%assoc_old%]) else (echo Association not yet taken)
)
rem Find a new, unused association
rem Note that we assume that we find one, eventually. This isn't guaranteed, but we'll ignore that for the moment
rem Otherwise this loop might run forever
:loop
set assoc_new=My.%1.%RANDOM%
if defined DEBUG echo Trying new association (%assoc_new%)
assoc .%1 >nul 2>nul
if errorlevel 1 (
set assoc_new=
if defined DEBUG echo Didn't work out
) else (
if defined DEBUG echo Found one! \o/
)
if not defined assoc_new goto loop
if defined DEBUG echo Writing reset batch file
echo @echo off>reset.cmd
echo assoc .%1=%assoc_old%>>reset.cmd
echo ftype %assoc_new%=>>reset.cmd
if defined DEBUG echo Writing setting batch file
echo @echo off>set.cmd
echo assoc .%1=%assoc_new%>>set.cmd
echo ftype %assoc_new%=%2 %%1>>set.cmd
goto :eof
:Usage
echo.Usage
echo. %~nx0 type command
echo.
echo. type is the file type to override, such as docx or txt.
echo. No dot before it is necessary.
echo. command is the command to perform on that file.
echo. %%1 is automatically appended at the end.
echo. If the command includes spaces, surround it with quotes.
echo.
echo.Example
echo. %~nx0 txt notepad
exit /b 1
这确实做的关联,但并没有解决重置协会回以前的应用程序的问题,但我打勾你反正是你的解决方案运作良好,对我来说足够。 – soupagain 2010-01-31 13:10:19
@soup:啊,对不起。我没有看过你的问题,就好像有一个以前的应用程序关联。可能首先查询以前的关联并动态地写入另一个批处理文件以恢复它。我会试试它是否够简单;只要坚持:-) – Joey 2010-01-31 13:12:05
@soup:编辑完毕;有一个批处理文件来测试。看起来,这不作为非管理员用户,但;可悲的是,这大大降低了它的价值。 – Joey 2010-01-31 17:42:03