我正在尝试确定用户输入的字符串对于表示文件夹路径是否有效.有效,我的意思是格式正确.
I am trying to determine whether a string input by a user is valid for representing a path to a folder. By valid, I mean formatted properly.
在我的应用程序中,该文件夹代表一个安装目的地.假设文件夹路径是有效,我想确定文件夹是否存在,如果不存在则创建它.
In my application, the folder represents an installation destination. Provided that the folder path is valid, I want to determine if the folder exists, and create it if it does not.
我目前正在使用 IO.Directory.Exists( String path ).我发现这很好用,除非用户没有正确格式化字符串.发生这种情况时,此方法将返回 false,表示该文件夹不存在.但这是一个问题,因为之后我将无法创建文件夹.
I am currently using IO.Directory.Exists( String path ). I find that this works fine except when the user does not format the string properly. When that happens, this method will return false which indicates that the folder does not exist. But this is a problem because I won't be able to create the folder afterwards.
从我的谷歌搜索中,我发现了一个使用正则表达式来检查格式是否正确的建议.我没有使用正则表达式的经验,我想知道这是否是一种可行的方法.这是我发现的:
From my googling I found a suggestion to use a regular expression to check if the format is proper. I have no experience with regular expressions, and am wondering if that is a viable approach. Here's what I found:
Regex r = new Regex( @"^(([a-zA-Z]:)|(\))(\{1}|((\{1})[^\]([^/:*?<>""|]*))+)$" ); return r.IsMatch( path );是否将正则表达式测试与 Directory.Exists() 结合起来,给我一个足够好的方法来检查路径是否有效以及它是否存在?我知道这会因操作系统和其他因素而异,但该程序仅面向 Windows 用户.
Would a regular expression test in combination with Directory.Exists(), give me a good enough method to check if the path is valid and whether it exists? I know this will vary with the OS and other factors, but the program is targeted for Windows users only.
推荐答案调用 Path.GetFullPath;如果路径无效,则会抛出异常.
Call Path.GetFullPath; it will throw exceptions if the path is invalid.
要禁用相对路径(例如 Word),请调用 Path.IsPathRooted.
To disallow relative paths (such as Word), call Path.IsPathRooted.
更多推荐
检查字符串是否是有效的 Windows 目录(文件夹)路径
发布评论