C# - Check if a given url is file or directory?

我与影子孤独终老i 提交于 2019-12-13 13:06:30

问题


I have a method which will input either a http , ftp or a local path. With the input url, i need to decide whether it is a file or directory.

Path.GetExtension(url) works almost fine. But if a directory begins with/have '.' in its name, then this checking will fail.

Is there any other methods to check and list url if directory ?


回答1:


You could use File.Exists(url) and Directory.Exists(url)

Another approach would be to create an array of extensions then check the result Path.GetExtension(url) against it.




回答2:


The following code takes the path, looks at the last substring (after the last /) and checks if there is a '.' in that substring to determine if it is a file or a path. isFile will be a boolean, true meaning that it is a file.

var isFile = new Uri(url).AbsolutePath.Split('/').Last().Contains('.');




回答3:


You can use URI.isFile property to see if the URI has a file in its path. If not, it is a directory.

Uri uriAddress2 = new Uri("https://www.google.com/testFile.txt");
if (uriAddress2.IsFile)
    Console.WriteLine("URI is a file.");
else
    Console.WriteLine("URI is a directory.");
// Output: "URI is a file."


来源:https://stackoverflow.com/questions/13116985/c-sharp-check-if-a-given-url-is-file-or-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!