C#无法创建目录

本文关键字:创建目录 | 更新日期: 2023-09-27 18:19:38

我似乎无法让以下代码工作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace TechKit
{
   class CsvWriter
   {
      public static void csvLogWrite(string ADName, string LogTimeStamp, string LogEntry, string ATOW, string SSC, string Specialty)
      {
         string dirPath = Path.GetDirectoryName(Properties.Settings.Default.TechKitSDFLocation);
         dirPath = Path.Combine(dirPath, "Logs", DateTime.Now.Year.ToString());
         try
         {
            // Determine whether the directory exists. 
            if (Directory.Exists(dirPath))
            {
               Console.WriteLine("Log Path Exisits - Using It");
               return;
            }
            // Try to create the directory.
            DirectoryInfo di = Directory.CreateDirectory(dirPath);
            Console.WriteLine("The Log directory was created successfully at {0}.", Directory.GetCreationTime(dirPath));
         }
         catch (Exception e)
         {
            Console.WriteLine("The directory creation process failed: {0}", e.ToString());
         }
         finally { }
         string newFileName = DateTime.Now.Month.ToString() + ".csv";
         string combinedPath = Path.Combine(dirPath, newFileName);
         string logDetails = LogTimeStamp + "," + Specialty + "," + ADName + "," + LogEntry + Environment.NewLine;
         if (!File.Exists(combinedPath))
         {
            string logHeader = "Timestamp,Specialty,Name,Log Entry" + Environment.NewLine;
            File.WriteAllText(newFileName, logHeader);
         }
         File.AppendAllText(combinedPath, logDetails);
         Console.WriteLine("Data Written To CSV FIle:");
         Console.WriteLine(logDetails);
         Console.WriteLine("****************************");
      }
   }
}

当代码试图写入不存在的目录时,会引发异常。我得到:

'A first chance exception of type 'System.NotSupportedException' occurred in mscorlib.dll'

在控制台中。我是一个相对的新手,所以我不知所措。我可以写一个文件,只是不创建目录。

谢谢。。。

C#无法创建目录

检查目录路径然后检查它的读/写权限。

然后使用类似的代码

DirectoryInfo dir = new DirectoryInfo(dirPath);
or 
System.IO.Director.CreateDirectory("Path to directory" )