【问题标题】:How to create a folder dynamically? [duplicate]如何动态创建文件夹? [复制]
【发布时间】:2014-07-23 22:22:58
【问题描述】:

我创建了一个 wpf 应用程序,我需要创建一个文件夹,并且在该文件夹中我希望在应用程序安装文件夹中动态创建一个文本文件

C:\Program Files (x86)\MyApplication\NewFolder\Mytext.txt\

同样明智。

我已经尝试了以下代码,但它没有得到

using System.IO;

private void CreateIfMissing(string path)
{
  bool folderExists = Directory.Exists(Server.MapPath(path));//Here i don't understand what is server i think this will work in ASP.NET
  if (!folderExists)
  Directory.CreateDirectory(Server.MapPath(path));
}

如何做到这一点?

【问题讨论】:

  • 谷歌是你的朋友:*.com/a/9065650/1387161
  • File.Create。这没有帮助吗?
  • 如果您只是尝试寻找答案,这将非常简单且微不足道。你能展示你尝试过的东西吗?听起来您只是在要求我们为您做这件事。
  • 如果您输入“c# create file”,这是您 Google 搜索中的第一件事
  • 如果您已将其标记为 WPF,为什么还要使用 Server.MapPath?

标签: c# wpf


【解决方案1】:

首先导入 C#/.NET 的 IO 库

using System.IO;

检查它是否存在,如果不存在,则使用以下内容创建它。

 if (!Directory.Exists(@"C:\Program Files (x86)\MyApplication\NewFolder")
       Directory.CreateDirectory(@"C:\Program Files (x86)\MyApplication\NewFolder");

老实说,如果您进行一些研究,哥们,您会找到的!祝你的项目好运

【讨论】:

  • 您好,实际上我已经尝试过您提供的代码,但我收到错误消息,表示该文件夹的访问被拒绝,它完全适用于除我想要的其他路径。
  • 使用 System.IO; /** * @returns A StreamWriter 如果没有发生异常,或者如果发生任何事情,则返回 null 对象 */ private StreamWriter CreatIfMissing(string path) { StreamWriter writer = null;字符串 newFolderPath = 路径 + @"\NewFolder"; if(!Directory.Exists(newFolderPath)) { 尝试 { Directory.CreateDirectory(newFolderPath); } 捕捉{} } 字符串 newFilePath = newFolderPath + @"\MyText.txt";尝试 { writer = File.CreateText(newFilePath); } 捕捉{} 返回作家; }
  • 您正在使用的帐户正在失效。这是您对该目录的 NTFS 权限。确保您使用的用户帐户具有创建/修改权限。委派一个管理员帐户,并以能够操作 NT 文件系统的帐户身份运行 .NET 代码。
  • 在 Windows Vista 及更高版本上,该文件夹(程序文件)受到保护。您不能在该文件夹中创建文件。您应该使用 AppData 的预定义文件夹:var folder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApplication");
  • 谢谢你们,谢谢你们的帮助:)