2012-05-04 66 views
4

我有一个接受文件路径的函数。用户可以将绝对路径或相对路径传递给文件。如果提供了一个相对路径,则ExpandPath功能,可以将其转换为绝对路径,像这样:如何在ColdFusion中确定文件路径是绝对还是相对的

<cfset filepath = ExpandPath("data/test.txt") > 

..它返回:

C:\www\example\data\test 

但是,如果用户提供了像绝对路径:

<cfset filepath = ExpandPath("C:\www\example\data\test") > 

..它返回:

C:\www\example\C:\www\example\data\test 

我该如何解决这个问题?

回答

3

你可以测试这个字符串,看看它是以C:\开头的windows还是\\为unix,并用它作为if? 这可能是你的窗口查询:

<cfif reFindNoCase("[a-zA-Z]:\\",myFileLocation)> 
    <!--- Is a absolute path ---> 
<cfelse> 
    <!--- Is not an absolute path ---> 
</cfif> 
+1

如果你正在做reFindNoCase,你不需要在正则表达式中指定两种情况!另外,在Windows上使用'C:/'提供CF是完全有效的。所以你要用'[a-z]:[\\ /]'这样做。 (尽管我更倾向于使用Al的方法。) –

7

一个可能更灵活的方式做,这是检查是否从原料输入的目录是否存在,如果没有,尝试expandpath。就像这样:

<cfif directoryExists(myFileLocation)> 
    <cfset theDirectory=myFileLocation)> 
<cfelseif directoryExists(expandPath(myFileLocation))> 
    <cfset theDirectory=expandPath(myFileLocation)> 
<cfelse> 
    <cfthrow message="Invalid directory!"> 
</cfif> 
相关问题