电竞比分网-中国电竞赛事及体育赛事平台

分享

創(chuàng)建文件或文件夾(C# 編程指南)

 *我愛陽(yáng)光* 2010-10-07

此示例在計(jì)算機(jī)上創(chuàng)建一個(gè)文件夾和一個(gè)子文件夾,然后在該子文件夾中創(chuàng)建一個(gè)新文件并將一些數(shù)據(jù)寫入該文件。

示例

 
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 不執(zhí)行任何操作,且不會(huì)引發(fā)異常。而 File.Create 則會(huì)覆蓋任何現(xiàn)有文件。若要避免覆蓋現(xiàn)有文件,可以使用 OpenWrite() 方法并指定將使文件被追加而不是被覆蓋的 FileMode.OpenOrCreate 選項(xiàng)。

以下情況可能會(huì)導(dǎo)致異常:

  • 文件夾名稱格式不正確。例如,它包含非法字符或僅僅是空白(ArgumentException 類)。使用 Path 類創(chuàng)建有效路徑名。

  • 要?jiǎng)?chuàng)建的文件夾的父文件夾是只讀的(IOException 類)。

  • 文件夾名稱是 nullArgumentNullException 類)。

  • 文件夾名稱太長(zhǎng)(PathTooLongException 類)。

  • 文件夾名稱只是冒號(hào)“:”(PathTooLongException 類)。

安全性

在部分信任的情況下可能會(huì)引發(fā) SecurityException 類的實(shí)例。

如果用戶不具有創(chuàng)建文件夾的權(quán)限,則該示例引發(fā) UnauthorizedAccessException 類的實(shí)例。

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多