当部分路径不存在时,File.Create()方法失败

时间:2018-12-30 20:43:27

标签: c# createfile

作为项目练习的一部分,我一直在编写一个简单的控制台应用程序。任务非常简单:

第二种方法必须创建嵌套目录树,其中每个文件夹名称均为Guid。

第三种方法必须将空文件放在特定级别的所选目录树中。

我的主要问题在于第三种方法。因为尽管它可以正常工作并且可以创建文件“直到任何目录的第三级”,但在那之后,它总是抛出“ System.IO.DirectoryNotFoundException”-因为它“找不到路径的一部分”。

我使用字符串作为路径的容器,但是由于很少有Guid设置在一起,所以它变得很长。我在创建目录时遇到了类似的问题,但是为了正常工作,我只需要在路径后面加上@“ \?\”前缀即可。那么有什么方法可以使它工作,或者解决它?

这是失败的方法。具体来说是

  

File.Create(PathToFile + @“ \ blank.txt”)。Dispose();

还有一部分代码将创建字符串并调用它:

string ChosenDirectoryPath = currDir.FullName + @"\";

for (int i = 0; i <= Position; i++)
{
   ChosenDirectoryPath += ListsList[WhichList][i];
}
if (!File.Exists(ChosenDirectoryPath + @"\blank.txt"))
{
   FileMaker(ref ChosenDirectoryPath);
}

编辑:

具体来说,目录是通过方法建立的:

public List<string> DirectoryList = new List<string>();
internal static List<List<string>> ListsList = new List<List<string>>();
private static DirectoryInfo currDir = new DirectoryInfo(".");
private string FolderName;
private static string DirectoryPath;

public void DeepDive(List<string> DirectoryList, int countdown)
{
   FolderName = GuidMaker();
   DirectoryList.Add(FolderName + @"\");

   if (countdown <= 1)
   {
      foreach (string element in DirectoryList)
      {
         DirectoryPath += element;
      }

      Directory.CreateDirectory(@"\\?\" + currDir.FullName + @"\" + DirectoryPath);
      Console.WriteLine("Folders were nested at directory {0} under folder {1}\n", currDir.FullName, DirectoryList[0]);

      ListsList.Add(DirectoryList);
      DirectoryPath = null;

      return;
   }
   DeepDive(DirectoryList, countdown-1);
}

由于递归,这很混乱(迭代会更好,但我想通过这种方式来学习一些东西)。关键是要建立目录并将其存储在列表列表中。

创建文件正常工作,但仅适用于前三个嵌套文件夹。因此问题在于,它在某种程度上失去了第4级和第5级归档的路径,甚至无法手动进行创建。路径可能太长了吗?以及解决方法。

这是抛出的异常:

  

System.IO.DirectoryNotFoundException:“找不到路径的一部分   C:\ Some \ More \ Folders \ 1b0c7715-ee01-4df8-9079-82ea7990030f \ c6c806b0-b69d-4a3a-88d0-1bd8a0e31eb2 \ 9671f2b3-3041-42d5-b631-4719d36c2ac5 \ 6406f00f-7750-4b5 bcacef2b-e391-4799-b84e-f2bc55605d40 \ blank.txt”。

因此它抛出了文件的完整路径,但表示找不到它。

1 个答案:

答案 0 :(得分:3)

您的问题是File.Create不会为您创建相应的目录,而是会抛出System.IO.DirectoryNotFoundException

您必须使用System.IO.Directory.CreateDirectory()

自己创建这些目录

如果由于路径太长而发生此异常,则仍然可以像创建目录时一样使用“长路径语法(\\?\)”。

另请参阅以下问题:How to deal with files with a name longer than 259 characters?也有一个很好的article链接