为了创建目录,我们必须首先在c#中导入system.io命名空间。命名空间是一个库,允许您访问用于创建、复制、移动和删除目录的静态方法。
始终建议在 C# 中执行任何文件操作之前检查目录是否存在,因为编译器如果文件夹不存在,将抛出异常。
using System; using System.IO; namespace DemoApplication { class Program { static void Main(string[] args) { string folderName = @"D:\Demo Folder"; // If directory does not exist, create it if (!Directory.Exists(folderName)) { Directory.CreateDirectory(folderName); } Console.ReadLine(); } } }
上面的代码会在D:目录下创建一个Demo文件夹。
Directory.CreateDirectory 也可用于创建子文件夹。
using System; using System.IO; namespace DemoApplication { class Program { static void Main(string[] args) { string folderName = @"D:\Demo Folder\Sub Folder"; // If directory does not exist, create it if (!Directory.Exists(folderName)) { Directory.CreateDirectory(folderName); } Console.ReadLine(); } } }
上述代码将在 D: 目录中创建一个带有子文件夹的演示文件夹。
以上就是C#中如果文件夹不存在如何创建?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号