Csharp/CSharp Tutorial/File Directory Stream/File Copy

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Copy a file

using System; 
using System.IO;  
 
class MainClass { 
  public static void Main(string[] args) { 
    int i; 
    FileStream fin; 
    FileStream fout; 
 
    try { 
      fin = new FileStream("inputFile.txt", FileMode.Open); 
    } catch(FileNotFoundException exc) { 
      Console.WriteLine(exc.Message + "\nInput File Not Found"); 
      return; 
    } 
 
    try { 
      fout = new FileStream("outputFile.txt", FileMode.Create); 
    } catch(IOException exc) { 
      Console.WriteLine(exc.Message + "\nError Opening Output File"); 
      return; 
    } 
 
    try { 
      do { 
        i = fin.ReadByte(); 
        if(i != -1) 
           fout.WriteByte((byte)i); 
      } while(i != -1); 
    } catch(IOException exc) { 
      Console.WriteLine(exc.Message + "File Error"); 
    } 
 
    fin.Close(); 
    fout.Close(); 
  } 
}

Copying A File by using FileInfo

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo MyFile = new FileInfo(@"c:\Projects\Testing.txt");
    MyFile.Create();
    MyFile.CopyTo(@"c:\Folder\Testing.txt");
    //or
    MyFile.CopyTo(@"c:\Folder\Testing.txt", true);
  }
}

Writing data: copying from one stream to another

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.rupression;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
public class MainClass
{
    public static void Main()
    {
        using (Stream from = new FileStream("c:\\test.txt", FileMode.Open))
        using (Stream to = new FileStream("c:\\test2.txt", FileMode.OpenOrCreate))
        {
            int readCount;
            byte[] buffer = new byte[1024];
            while ((readCount = from.Read(buffer, 0, 1024)) != 0)
            {
                to.Write(buffer, 0, readCount);
            }
        }
    }
}