我有一个函数,Path通过确定String Path是a File还是a来自动创建指定的Directory.
通常情况下,我会使用此路径已经exists:
FileAttributes attributes = File.GetAttributes("//Path");
if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
Directory.CreateDirectory("//Path");
}
Run Code Online (Sandbox Code Playgroud)
但如果不是呢?如何检查是否String Path是File或Directory如果它不存在呢?
如果场景中的文件必须具有扩展名,则可以使用此方法.
注意:在Windows中使用目录中的句点是合法的,但这主要是为了跨文件的跨操作系统兼容性而引入的.在严格的Windows环境中,将文件没有扩展名或在目录名中放置句点或空格被认为是不好的形式.如果您不需要考虑该方案,那么您可以使用此方法.如果不是,您将不得不通过链或结构发送某种标志以识别字符串的意图.
var ext = System.IO.Path.GetExtension(strPath);
if(ext == String.Empty)
{
//Its a path
}
Run Code Online (Sandbox Code Playgroud)
如果您不需要对文件类型进行任何分析,您可以像下面这样简单:
if(System.IO.Path.HasExtension(strPath))
{
//It is a file
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7967 次 |
| 最近记录: |