【问题标题】:how to create a file in c drive using C# in Windows7 OS如何在 Windows7 操作系统中使用 C# 在 C 盘中创建文件
【发布时间】:2010-12-09 05:29:23
【问题描述】:

如何在Windows7 OS中使用C#在c盘创建文件

【问题讨论】:

  • 我想我们可能需要更多信息。

标签: c# .net windows windows-7 file-io


【解决方案1】:

以下示例代码将在您的 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();
    }
}

通过阅读original MSDN How-To article查看所有血腥细节。

【讨论】:

    猜你喜欢
    • 2014-04-25
    • 2014-01-10
    • 1970-01-01
    • 2020-07-20
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多