分享

创建文件或文件夹(C# 编程指南)

 *我爱阳光* 2010-10-07

此示例在计算机上创建一个文件夹和一个子文件夹,然后在该子文件夹中创建一个新文件并将一些数据写入该文件。

示例

 
public class CreateFileOrFolder
{
    static void Main()
    {
        // Specify a "currently active folder"
        string activeDir = @"d:\testdir";

        //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 选项。

以下情况可能会导致异常:

安全性

在部分信任的情况下可能会引发 SecurityException 类的实例。

如果用户不具有创建文件夹的权限,则该示例引发 UnauthorizedAccessException 类的实例。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多