如何:创建文件或文件夹
2010-07-13 15:46
344 查看
此示例在计算机上创建一个文件夹和一个子文件夹,然后在该子文件夹中创建一个新文件并将一些数据写入该文件。
示例
public class CreateFileOrFolder
示例
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(); } } 如果该文件夹已存在,则 CreateDirectory 不执行任何操作,且不会引发异常。而 File.Create 则会覆盖任何现有文件。若要避免覆盖现有文件,可以使用 OpenWrite()方法并指定将使文件被追加而不是被覆盖的 FileMode.OpenOrCreate 选项。 以下情况可能会导致异常: 文件夹名称格式不正确。例如,它包含非法字符或仅仅是空白(ArgumentException 类)。使用 Path 类创建有效路径名。 要创建的文件夹的父文件夹是只读的(IOException 类)。 文件夹名称是 null(ArgumentNullException 类)。 文件夹名称太长(PathTooLongException 类)。 文件夹名称只是冒号“:”(PathTooLongException 类)。
相关文章推荐
- Java 在给定路径上创建文件,所在文件夹不存在时,如何正确创建
- Java如何判断文件或者文件夹是否在?不存在如何创建?
- Java如何在不存在文件夹的目录下创建文件
- 如何在xcode中创建新的文件和文件夹
- Java 在给定路径上创建文件,所在文件夹不存在时,如何正确创建。
- File中如何能创建多个新文件夹,并在新文件夹中创建新文件呢?
- php判断文件夹或文件是否存在,及不存在时如何创建
- 如何创建,删除名字以中划线开头的文件或文件夹
- Fedora中如何创建文件夹和创建文件
- C# 创建文件时,文件夹不存在,如何自动创建文件夹
- Java 在给定路径上创建文件,所在文件夹不存在时,如何正确创建。
- 如何在xcode创建文件夹和文件--虚拟文件夹和物理文件夹的同步
- Java 在给定路径上创建文件,所在文件夹不存在时,如何正确创建。
- 如何在macos下创建文件或者文件夹的快捷方式
- MySQL5.6如何查找my.ini文件和创建的数据库文件夹
- Java基础之IO流判断文件夹或文件是否存在及其如何创建?
- Java如何判断文件或者文件夹是否在?不存在如何创建?
- 电脑如何创建共享文件、文件夹
- C# 如何获取某文件夹的文件列表,并按文件的创建时间排序?
- 如何在xcode创建文件夹和文件