この例では、コンピューター上にフォルダーとサブフォルダーを作成し、サブフォルダー内に新しいファイルを作成して、ファイルにデータを書き込みます。
使用例
public class CreateFileOrFolder
{
static void Main()
{
// Specify a "currently active folder"
string activeDir = @"c:\testdir2";
//Create a new subfolder under the current active folder
string newPath = System.IO.Path.Combine(activeDir, "mySubDir");
// Create the subfolder
System.IO.Directory.CreateDirectory(newPath);
// Create a new file name. This example generates
// a random string.
string newFileName = System.IO.Path.GetRandomFileName();
// Combine the new file name with the path
newPath = System.IO.Path.Combine(newPath, newFileName);
// Create the file and write to it.
// DANGER: System.IO.File.Create will overwrite the file
// if it already exists. This can occur even with
// random file names.
if (!System.IO.File.Exists(newPath))
{
using (System.IO.FileStream fs = System.IO.File.Create(newPath))
{
for (byte i = 0; i < 100; i++)
{
fs.WriteByte(i);
}
}
}
// Read data back from the file to prove
// that the previous code worked.
try
{
byte[] readBuffer = System.IO.File.ReadAllBytes(newPath);
foreach (byte b in readBuffer)
{
Console.WriteLine(b);
}
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
フォルダーが既に存在していた場合、CreateDirectory は何も実行せず、例外はスローされません。 ただし、File.Create は、既存のすべてのファイルを上書きします。 既存のファイルが上書きされないようにするには、OpenWrite メソッドを使用して、FileMode.OpenOrCreate オプションを指定します。これにより、ファイルへの上書きではなく追加が行われます。
次の条件を満たす場合は、例外が発生する可能性があります。
フォルダー名が不適切である場合。 たとえば、不正な文字が含まれている場合や、空白だけの場合などがその例です (ArgumentException クラス)。 有効なパス名を作成するには、Path クラスを使用します。
作成するフォルダーの親フォルダーが読み取り専用である場合 (IOException クラス)。
フォルダー名が null である場合 (ArgumentNullException クラス)。
フォルダー名が長すぎる場合 (PathTooLongException クラス)。
フォルダー名がコロン (":") だけである場合 (PathTooLongException クラス)。
セキュリティ
部分的に信頼された状況では、SecurityException クラスのインスタンスがスローされることがあります。
フォルダーの作成に必要なアクセス許可がユーザーに与えられていない場合、この例では UnauthorizedAccessException クラスのインスタンスがスローされます。