如何检查一个字符串是否是一个有效的Windows目录/文件夹路径? [英] How to check if a string is a valid Windows directory/folder path?

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

问题描述

我想检查,如果用户输入的字符串是一个有效的安装目标,然后检查它是否存在,如果不创建它。我的问题是与验证,以确保目标字符串格式正确无误。

I trying to check if the user-inputted string is a valid install destination, then check if it exists, and create it if not. My problem is with validating that the destination string is formatted properly.

我目前使用 IO.Directory.Exists(字符串路径)和作品除了当用户没有正确格式化字符串罚款。该方法将返回false,但我不能在事后创建文件夹。

I am currently using IO.Directory.Exists( String path ) and works fine except when the user did not format the string properly. That method will return false, but I won't be able to create the folder afterwards.

谷歌搜索建议我用正则表达式来检查格式正确。我有一个正则表达式0经验,我想知道这是否会工作。下面是我发现的:

Googling suggested I use regular expressions to check if the format is proper. I have 0 experience with regular expressions, and am wondering if that will work. Here's what I found:

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



这会在与 Directory.Exists()组合,给我的够好的方法来检查如果路径是有效的,它的存在?我知道这将与操作系统和其他因素而有所不同,但程序是针对窗口用户只。

Would this, in combination with Directory.Exists(), give me a good enough method to check if the path is valid and it exists? I know this will vary with 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.

要禁止相对路径(如),呼叫< A HREF =htt​​p://msdn.microsoft.com/en-us/library/system.io.path.ispathrooted> Path.IsPathRooted

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

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

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