验证在C#中的文件夹名称 [英] Validate folder name in C#

查看:567
本文介绍了验证在C#中的文件夹名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证在C#中的文件夹名称。

I need to validate a folder name in c#.

我曾尝试以下正则表达式:

I have tried the following regex :

 ^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$

但它失败,我使用 GetInvalidPathChars()也试过

当我尝试使用失败 Y:\abc 作为文件夹名即驱动器号:?\foldername

It fails when i try using P:\abc as a folder name i.e Driveletter:\foldername

任何人都可以说明为什么

Can anyone suggest why?

推荐答案

您可以这样做,以这种方式(使用 System.IO.Path.InvalidPathChars 常数):

You could do that in this way (using System.IO.Path.InvalidPathChars constant):

bool IsValidFilename(string testName)
{
    Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
    if (containsABadCharacter.IsMatch(testName) { return false; };

    // other checks for UNC, drive-path format, etc

    return true;
}



。如果你想有一个正则表达式验证的文件夹路径,那么你可以使用这一个:

[edit]
If you want a regular expression that validates a folder path, then you could use this one:

正则表达式的regex =新的正则表达式(^ ([A-ZA-Z]:)(\\\\ [^<>?:\/ \\\\ | *] +)?+ \\ ?\\ $);



我想起了一件棘手的事情,可以让你检查,如果路径是正确的:

[edit 2]
I've remembered one tricky thing that lets you check if the path is correct:

VAR invalidPathChars = Path.GetInvalidPathChars(路径)

或(对于文件):

VAR invalidFileNameChars =路径.GetInvalidFileNameChars(文件名)

这篇关于验证在C#中的文件夹名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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