检查字符串是否是有效的 Windows 目录(文件夹)路径

编程入门 行业动态 更新时间:2024-10-24 06:28:16
本文介绍了检查字符串是否是有效的 Windows 目录(文件夹)路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试确定用户输入的字符串对于表示文件夹路径是否有效.有效,我的意思是格式正确.

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 目录(文件夹)路径

本文发布于:2023-06-07 15:15:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568481.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   文件夹   路径   目录   Windows

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!