Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 捕获无效的文件路径_C# - Fatal编程技术网

C# 捕获无效的文件路径

C# 捕获无效的文件路径,c#,C#,我有一个函数,可以从文本文件中读取一组路径值(其中8或9个)。它稍后在应用程序中使用这些路径来读取文件。检查这些文件路径有效性的最佳方法是什么。我可以执行某种类型的单个捕获吗?System.IO.Directory.Exists(字符串路径) System.IO.File.Exists(字符串路径)我只是在循环中使用,非常简单且可读。有更时尚的方式吗?也许吧。也许正则表达式是您的一个选择,至少在windows环境中是这样。这避免了像File.Exists那样进行磁盘访问。资料来源: public

我有一个函数,可以从文本文件中读取一组路径值(其中8或9个)。它稍后在应用程序中使用这些路径来读取文件。检查这些文件路径有效性的最佳方法是什么。我可以执行某种类型的单个捕获吗?

System.IO.Directory.Exists(字符串路径)
System.IO.File.Exists(字符串路径)

我只是在循环中使用,非常简单且可读。有更时尚的方式吗?也许吧。

也许正则表达式是您的一个选择,至少在windows环境中是这样。这避免了像File.Exists那样进行磁盘访问。资料来源:

public bool IsValidPath(字符串路径)
{
正则表达式r=新正则表达式(@“^([a-zA-Z]\:)|(\\)(\{1}|)((\{1})[^\\]([^/:*?“\]*)+)$”;
返回r.IsMatch(路径);
}

您可以使用
文件。Exists
和/或
目录。Exists
是路径,也可以是目录

static void Main(string[] args)
{
    List<string> paths = new List<string>{"C:\\path1.txt", "c:\\path2.txt"};
    bool allValid = paths.All(path=>File.Exists(path));
}
static void Main(字符串[]args)
{
列表路径=新列表{“C:\\path1.txt”,“C:\\path2.txt”};
bool allValid=path.All(path=>File.Exists(path));
}

考虑使用该方法。与
Path
类的大多数成员一样,如果路径无效,它将验证您传入的路径,并抛出
ArgumentException

文件。如果有人锁定了文件,Exists
也将返回
false
。@John Saunders感谢您指出这一点,情况确实如此。
static void Main(string[] args)
{
    List<string> paths = new List<string>{"C:\\path1.txt", "c:\\path2.txt"};
    bool allValid = paths.All(path=>File.Exists(path));
}