如何检查我的系统的文件路径是否添加为字符串格式良好 [英] How to check if a file path of the my system is added as string is well formed
问题描述
我需要检查一个路径集是否正确为字符串:
示例:C:\ Intel \ Logs它应该返回true。
如果 C:\\ Intel \ Logs它应该返回false
我试过了下面的代码
bool isiValid = Uri.IswellFormedUri(@" C:\ Intel \ Logs",UriKind.RelativeOrAbsolute);
但是总是我得到isValid为假。
取决于你的意思是有效的。有效路径并不意味着它实际存在。要验证路径,您可以使用Uri,但您可能只想处理文件,而不是任何URL,因此您需要添加方案。也许是这样的。
class Program
{
static void Main(string [] args)
{
var paths = new []
{
@" C:\ Test",
@":a | b",
@" \ Temp",
@" .. \ Parent"
};
foreach(路径中的var路径)
Console.WriteLine(" {0}是{1}",路径,IsValidPath(路径)?"有效":"无效" );
}
静态bool IsValidPath(字符串路径)
{
返回Uri.TryCreate(Uri.UriSchemeFile + path,UriKind.RelativeOrAbsolute,out var uri);
}
}
如果要验证路径是否存在,可以使用
Directory.Exists 。
I need to check if a path set is as a string is correct:
Example : C:\Intel\Logs it should return true.
If C:\\Intel\Logs it should return false
I tried with the below code
bool isiValid = Uri.IswellFormedUri(@"C:\Intel\Logs",UriKind.RelativeOrAbsolute);
but always I am getting isValid as false.
Depends upon what you mean by valid. A valid path doesn't mean it actually exists. To validate a path you could use Uri but you probably want to handle only files, not any URL so you'll want to add the scheme. Maybe something like this.
class Program { static void Main ( string[] args ) { var paths = new[] { @"C:\Test", @":a|b", @"\Temp", @"..\Parent" }; foreach (var path in paths) Console.WriteLine("{0} is {1}", path, IsValidPath(path) ? "valid" : "invalid"); } static bool IsValidPath ( string path ) { return Uri.TryCreate(Uri.UriSchemeFile + path, UriKind.RelativeOrAbsolute, out var uri); } }If you want to verify that a path exists however you can use Directory.Exists.
这篇关于如何检查我的系统的文件路径是否添加为字符串格式良好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!