如何在Windows7操作系统中使用C#在c盘中创建文件

Sre*_*r P -2 .net c# windows file-io windows-7

如何在Windows7操作系统中使用C#在c盘中创建文件

Cod*_*ray 9

以下示例代码将在C:驱动器上创建一个文件夹和一个子文件夹,然后使用随机文件名在子文件夹中创建一个新文件.最后,一些数据将写入文件.(代码评论很好,你应该能够通过仔细研究来弄清楚发生了什么.)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

通过阅读原始的MSDN How-To文章,查看所有血腥细节.