ここに、ディレクトリが存在しない場合に壊れるコードがあります。
System.IO.File.WriteAllText(filePath, content);
1行(または数行)で、新しいファイルにつながるディレクトリが存在しないかどうかを確認し、存在しない場合は、新しいファイルを作成する前にそれを作成できますか?
.NET 3.5を使用しています。
ここに、ディレクトリが存在しない場合に壊れるコードがあります。
System.IO.File.WriteAllText(filePath, content);
1行(または数行)で、新しいファイルにつながるディレクトリが存在しないかどうかを確認し、存在しない場合は、新しいファイルを作成する前にそれを作成できますか?
.NET 3.5を使用しています。
回答:
(new FileInfo(filePath)).Directory.Create() ファイルに書き込む前。
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
              Task.Run(() => );。
                    次のコードを使用できます
  DirectoryInfo di = Directory.CreateDirectory(path);
              Directory.CreateDirectoryまさにあなたが望むことをします:それがまだ存在しない場合、それはディレクトリを作成します。最初に明示的なチェックを行う必要はありません。
                    pathであり、ディレクトリではない場合、IOExceptionをスローします。msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx
                    ファイルを存在しないディレクトリに移動するエレガントな方法は、ネイティブのFileInfoクラスに次の拡張機能を作成することです。
public static class FileInfoExtension
{
    //second parameter is need to avoid collision with native MoveTo
    public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) { 
        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));
            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }
        file.MoveTo(destination);
    }
}
次に、新しいMoveTo拡張機能を使用します。
 using <namespace of FileInfoExtension>;
 ...
 new FileInfo("some path")
     .MoveTo("target path",true);
メソッド拡張のドキュメントを確認してください。
あなたは使用することができますFile.Existsをファイルが存在するかどうかを確認するために、それは使用して作成しFile.Createを必要に応じて。その場所にファイルを作成するアクセス権があるかどうかを確認してください。
ファイルが存在することを確認したら、安全にファイルに書き込むことができます。予防策として、コードをtry ... catchブロックに入れて、予定どおりに機能しない場合に関数が発生する可能性のある例外をキャッチする必要があります。
var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));
var file = new FileInfo(filePath);
file.Directory.Create(); ディレクトリがすでに存在する場合、このメソッドは何もしません。
var sw = new StreamWriter(filePath, true);
sw.WriteLine(Enter your message here);
sw.Close();