简体   繁体   English

检查给定的路径字符串是否无效

[英]check if the path string given is invalid

I have here a textbox that should accept a file path. 我这里有一个应该接受文件路径的文本框。 How should I validate (by a button click) whether the given path file do exists or not? 我应该如何验证(通过按钮单击)给定的路径文件是否存在?

For example, "C:MyDocs\\sample.txt" should be invalid because it is not actually existing in my local drive and there's no '\\' after 'C:'.. 例如,“C:MyDocs \\ sample.txt”应该无效,因为它实际上并不存在于我的本地驱动器中,并且在'C:'之后没有'\\'..

i have tried using this: 我试过用这个:

FileInfo fi = new FileInfo(fName);
 if (fi.Exists)
    //do something

but it doesn't satisfy my issue..can anyone advise? 但它不能满足我的问题......任何人都可以提出建议吗?

if(!File.Exists(filename))
{
// file does not exist or path is invalid
}

use Uri.IsWellFormedUriString(path, UriKind.Absolute); 使用Uri.IsWellFormedUriString(path, UriKind.Absolute); to check if the path is valid (beside if the file exists) 检查路径是否有效(如果文件存在,则旁边)

read here for Uri validation: http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx 在这里阅读Uri验证: http//msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx

Sample: 样品:

bool isValid = Uri.IsWellFormedUriString(fName, UriKind.Absolute) &&
               File.Exists(fName);

if the result is true, you can know for sure that the file format supplied by the user is valid and the file exists @ the file system. 如果结果为true,则可以确定用户提供的文件格式是否有效且文件系统是否存在文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM