【问题标题】:String path validation字符串路径验证
【发布时间】:2012-10-08 11:36:13
【问题描述】:

我这里有一个文件路径的字符串(来自用户的输入)。我检查了字符串,以便它符合条件:

  • 检查文件路径的无效字符
  • 不接受绝对路径 (\Sample\text.txt)

无效字符是:

: " / \ | ? *

我尝试在 catch 子句中捕获这些无效字符。它工作除了'\'。它将接受 'C:\\Sample\text.txt' 这是一个无效的文件路径。

以下示例应为无效路径:

  • :\text.txt
  • :text.txt
  • \:text.txt
  • \text.txt
  • C:\\\text.txt

ff.是一个有效路径的例子:

  • C:\text.txt

我遇到过类似的问题,但似乎都没有解决我的问题。

进行此类检查的最佳方法是什么?

【问题讨论】:

  • 什么是有效路径?
  • 你想说如果路径有“\”或“/”是无效的?
  • 我已经编辑了我的问题,列出了无效字符列表..

标签: c# path


【解决方案1】:

你可以使用Path.GetFullPath,如果路径无效会抛出异常。你可以有这样的方法:

public static bool IsValidPath(string path)
{
    try
    {
       path = path.Replace(@"\\", ":"); // to cancel out c:\\\\test.text
       string temp = Path.GetPathRoot(path); //For cases like: \text.txt
       if (temp.StartsWith(@"\"))
            return false;
       string pt = Path.GetFullPath(path);
    }
    catch //(Exception NotSupportedException) // catch specific exception here or not if you want
    {
        return false;
    }
    return true;
}

要测试的示例代码:

List<string> list = new List<string>()
{
    @":\text.txt",
    @":text.txt",
    @"\:text.txt",
    @"\text.txt",
    @"C:\\\text.txt",
    @"C:\text.txt",

};

foreach(string str in list)
{
    Console.WriteLine("Path: {0} is Valid = {1}" ,str,IsValidPath(str));
}

输出:

Path: :\text.txt is Valid = False
Path: :text.txt is Valid = False
Path: \:text.txt is Valid = False
Path: \text.txt is Valid = False
Path: C:\\\text.txt is Valid = False
Path: C:\text.txt is Valid = True

【讨论】:

  • 此解决方案在 C:\\Sample\text.txt 和 C:\\\text.txt 上有效。但是它们在 Windows 中有效。
  • @AndreyStukalin,Path.GetFullPath,忽略 (\\) 并考虑一次,您可以将其替换为一些无效字符,如 :,然后检查。我已经更新了答案。谢谢指出
  • 当“C:\\\text.txt”被输入时,我会得到Path.GetFullPath(path),“C:\text.txt”被返回..
  • @CMAñora,你试过编辑版本吗,我用:替换了双反斜杠?
  • @Habib 现在。很抱歉
【解决方案2】:

使用 regex.match() 方法进行文件路径验证:

Match match = Regex.Match(input, ^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(?i)(txt|gif|pdf|doc|docx|xls|xlsx)$,
        RegexOptions.IgnoreCase);

【讨论】:

  • D:\Main\sitename Research\Project_Mayank\Project.Web\StaticResources\2012\ClientPrint\6319522\NY 1120New York Blank Forms (2).pdf 不适合我。可能是什么原因?
猜你喜欢
  • 2021-12-25
  • 2011-12-08
  • 2022-01-06
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
相关资源
最近更新 更多