检查一个字符串是否是有效的Windows目录(文件夹)路径 [英] Check if a string is a valid Windows directory (folder) path

查看:256
本文介绍了检查一个字符串是否是有效的Windows目录(文件夹)路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确定一个用户输入的字符串是否有效表示一个文件夹的路径。通过有效的,我的意思是格式正确。



在我的应用程序中,该文件夹代表安装目标。如果文件夹路径,我想确定文件夹是否存在,如果不存在,就创建它。



我目前使用 IO.Directory.Exists(String path)。我发现这工作正常,除非用户不正确格式化字符串。发生这种情况时,此方法将返回false,表示该文件夹不存在。但是,这是一个问题,因为我将无法创建文件夹。



从我的谷歌搜索,我发现了一个建议,使用正则表达式来检查格式是适当的。我没有正则表达式的经验,我想知道这是否是一个可行的方法。这是我发现的:

pre $ Regex r = new Regex(@^(([a-zA-Z] \: )|(\\))(\\ {1} |((\\ {1})[^ \\]([^ /?* LT;> 中 |] *))+)$);
return r.IsMatch(path);

将正则表达式测试与 Directory.Exists() code>,给我一个足够好的方法来检查路径是否有效,是否存在?我知道这将随着操作系统和其他因素而变化,但该程序仅针对 Windows 用户。

>

呼叫 路径。 GetFullPath ;如果路径无效,它将抛出异常。



要禁止相对路径(例如 Word ),请调用< a href =http://msdn.microsoft.com/en-us/library/system.io.path.ispathrooted =noreferrer> Path.IsPathRooted


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.

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 );

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.

解决方案

Call Path.GetFullPath; it will throw exceptions if the path is invalid.

To disallow relative paths (such as Word), call Path.IsPathRooted.

这篇关于检查一个字符串是否是有效的Windows目录(文件夹)路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆