总结C#中,关于文件和文件夹的一些常见操作:
获得当前(执行的程序所在的)路径
核心代码:
1 | System.Environment.CurrentDirectory |
官网解释:
Environment.CurrentDirectory 属性
示例代码:
1 | string currentPath = System.Environment.CurrentDirectory; |
合并(多个,文件夹加上文件的)路径
核心代码:
1 | Path.Combine |
官网解释:
示例代码:
1 2 3 4 5 | using System.IO; string currentPath = System.Environment.CurrentDirectory; string outputFilename = "fiverrComScrapedResult.xls" ; string fullFilename = Path.Combine(currentPath, outputFilename); |
判断文件是否存在
核心代码:
1 | System.IO.File.Exists |
官网解释:
示例代码:
1 2 | string fileForTest = "D:\\download\\503aec99594da.doc" ; bool fileIsOk = System.IO.File.Exists(fileForTest); |
注意事项:
- 不应使用 Exists 方法来验证路径,此方法仅检查 path 中指定的文件是否存在。将无效路径传递到 Exists 返回 false。
判断文件夹是否存在
核心代码:
1 | System.IO.Directory.Exists |
官网解释:
示例代码:
1 2 | string folderToTest = "D:\\download" ; bool dirOk = System.IO.Directory.Exists(folderToTest); |
转载请注明:在路上 » 【总结】C#中关于文件和文件夹的常见操作