打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

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

示例

 
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 类的实例。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C#操作目录和文件
JAVA文件操作类
C# 读取文件内容
VA18.0 文件命名空间及基础概念
C#获取文件夹下的所有文件的文件名
BarCode Reader SDK使用教程:如何解PDF147码
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服