欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#程序中创建、复制、移动、删除文件或文件夹的示例

程序员文章站 2023-09-07 19:12:34
创建文件或文件夹 您可通过编程方式在您的计算机上创建文件夹、子文件夹和子文件夹中的文件,并将数据写入文件。 public class createfileorf...

创建文件或文件夹

您可通过编程方式在您的计算机上创建文件夹、子文件夹和子文件夹中的文件,并将数据写入文件。

public class createfileorfolder
{
  static void main()
  {
    string foldername = @"c:\top-level folder";

    string pathstring = system.io.path.combine(foldername, "subfolder");

    string pathstring2 = @"c:\top-level folder\subfolder2";

    system.io.directory.createdirectory(pathstring);

 
    string filename = system.io.path.getrandomfilename();

    pathstring = system.io.path.combine(pathstring, filename);

    console.writeline("path to my file: {0}\n", pathstring);

    if (!system.io.file.exists(pathstring))
    {
      using (system.io.filestream fs = system.io.file.create(pathstring))
      {
        for (byte i = 0; i < 100; i++)
        {
          fs.writebyte(i);
        }
      }
    }
    else
    {
      console.writeline("file \"{0}\" already exists.", filename);
      return;
    }

    try
    {
      byte[] readbuffer = system.io.file.readallbytes(pathstring);
      foreach (byte b in readbuffer)
      {
        console.write(b + " ");
      }
      console.writeline();
    }
    catch (system.io.ioexception e)
    {
      console.writeline(e.message);
    }

    system.console.writeline("press any key to exit.");
    system.console.readkey();
  }

}

输出:
path to my file: c:\top-level folder\subfolder\ttxvauxe.vv0

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 8
3 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

如果该文件夹已存在,则 createdirectory 不执行任何操作,且不会引发异常。但是,file.create 用新的文件替换现有文件。该示例使用一个 if-else 语句阻止现有文件被替换。
通过在示例中做出以下更改,您可以根据具有某个名称的程序是否存在来指定不同的结果。如果该文件不存在,代码将创建一个文件。如果该文件存在,代码将把数据添加到该文件中。
指定一个非随机文件名。

// comment out the following line.
//string filename = system.io.path.getrandomfilename();

// replace that line with the following assignment.
string filename = "mynewfile.txt";

用以下代码中的 using 语句替换 if-else 语句。

using (system.io.filestream fs = new system.io.filestream(pathstring, filemode.append)) 
{
  for (byte i = 0; i < 100; i++)
  {
    fs.writebyte(i);
  }
}

运行该示例若干次以验证数据是否每次都添加到文件中。

复制、删除和移动文件和文件夹
以下示例说明如何使用 system.io 命名空间中的 system.io.file、system.io.directory、system.io.fileinfo 和 system.io.directoryinfo 类以同步方式复制、移动和删除文件和文件夹。 这些示例没有提供进度栏或其他任何用户界面。

示例
下面的示例演示如何复制文件和目录。

public class simplefilecopy
{
  static void main()
  {
    string filename = "test.txt";
    string sourcepath = @"c:\users\public\testfolder";
    string targetpath = @"c:\users\public\testfolder\subdir";

    // use path class to manipulate file and directory paths.
    string sourcefile = system.io.path.combine(sourcepath, filename);
    string destfile = system.io.path.combine(targetpath, filename);

    // to copy a folder's contents to a new location:
    // create a new target folder, if necessary.
    if (!system.io.directory.exists(targetpath))
    {
      system.io.directory.createdirectory(targetpath);
    }

    // to copy a file to another location and 
    // overwrite the destination file if it already exists.
    system.io.file.copy(sourcefile, destfile, true);

    // to copy all the files in one directory to another directory.
    // get the files in the source folder. (to recursively iterate through
    // all subfolders under the current directory, see
    // "how to: iterate through a directory tree.")
    // note: check for target path was performed previously
    //    in this code example.
    if (system.io.directory.exists(sourcepath))
    {
      string[] files = system.io.directory.getfiles(sourcepath);

      // copy the files and overwrite destination files if they already exist.
      foreach (string s in files)
      {
        // use static path methods to extract only the file name from the path.
        filename = system.io.path.getfilename(s);
        destfile = system.io.path.combine(targetpath, filename);
        system.io.file.copy(s, destfile, true);
      }
    }
    else
    {
      console.writeline("source path does not exist!");
    }

    // keep console window open in debug mode.
    console.writeline("press any key to exit.");
    console.readkey();
  }
}


下面的示例演示如何移动文件和目录。

public class simplefilemove
{
  static void main()
  {
    string sourcefile = @"c:\users\public\public\test.txt";
    string destinationfile = @"c:\users\public\private\test.txt";

    // to move a file or folder to a new location:
    system.io.file.move(sourcefile, destinationfile);

    // to move an entire directory. to programmatically modify or combine
    // path strings, use the system.io.path class.
    system.io.directory.move(@"c:\users\public\public\test\", @"c:\users\public\private");
  }
}


下面的示例演示如何删除文件和目录。

public class simplefiledelete
{
  static void main()
  {
    // delete a file by using file class static method...
    if(system.io.file.exists(@"c:\users\public\deletetest\test.txt"))
    {
      // use a try block to catch ioexceptions, to
      // handle the case of the file already being
      // opened by another process.
      try
      {
        system.io.file.delete(@"c:\users\public\deletetest\test.txt");
      }
      catch (system.io.ioexception e)
      {
        console.writeline(e.message);
        return;
      }
    }

    // ...or by using fileinfo instance method.
    system.io.fileinfo fi = new system.io.fileinfo(@"c:\users\public\deletetest\test2.txt");
    try
    {
      fi.delete();
    }
    catch (system.io.ioexception e)
    {
      console.writeline(e.message);
    }

    // delete a directory. must be writable or empty.
    try
    {
      system.io.directory.delete(@"c:\users\public\deletetest");
    }
    catch (system.io.ioexception e)
    {
      console.writeline(e.message);
    }
    // delete a directory and all subdirectories with directory static method...
    if(system.io.directory.exists(@"c:\users\public\deletetest"))
    {
      try
      {
        system.io.directory.delete(@"c:\users\public\deletetest", true);
      }

      catch (system.io.ioexception e)
      {
        console.writeline(e.message);
      }
    }

    // ...or with directoryinfo instance method.
    system.io.directoryinfo di = new system.io.directoryinfo(@"c:\users\public\public");
    // delete this dir and all subdirs.
    try
    {
      di.delete(true);
    }
    catch (system.io.ioexception e)
    {
      console.writeline(e.message);
    }

  }
}