文件Copy有以下幾種方法:
1.Copy
string sourceFile = @"c:\temp\New Text Document.txt"; string destinationFile = @"c:\temp\test.txt"; bool isrewrite=true; // true=覆蓋已存在的同名文件,false則反之 System.IO.File.Copy(sourcePath, targetPath, isrewrite);
2.CopyTo
string sourceFile = @"c:\temp\New Text Document.txt"; string destinationFile = @"c:\temp\test.txt"; FileInfo file = new FileInfo(sourceFile); if (file.Exists) { // true is overwrite file.CopyTo(destinationFile, true); }
3.使用文件流讀寫來實現Copy
#region 拷貝操作 private void button3_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); DialogResult res = ofd.ShowDialog(); if (res == DialogResult.OK) { if (!string.IsNullOrEmpty(ofd.FileName)) { //1.創建讀入文件流對象 FileStream streamRead = new FileStream(ofd.FileName, FileMode.Open); //2.創建1個字節數組,用於接收文件流對象讀操作文件值 byte[] data = new byte[1024 * 1024];//1M int length = 0; SaveFileDialog sfd = new SaveFileDialog(); DialogResult sres = sfd.ShowDialog(); if (sres == DialogResult.OK) { if (!string.IsNullOrEmpty(ofd.FileName)) { FileStream streamWrite = new FileStream(sfd.FileName, FileMode.Create); do { //3.文件流讀方法的參數1.data-文件流讀出數據要存的地方,2. 0--從什么位置讀,3. data.Length--1次讀多少字節數據 //3.1 Read方法的返回值是一個int類型的,代表他真實讀取 字節數據的長度, length = streamRead.Read(data, 0, data.Length);//大文件讀入時候,我們定義字節長度的可能會有限,如果文件超大,要接收文件流對象的Read()方法,會返回讀入的實際長度 //加密 和解密 for (int i = 0; i < length; i++) { data[i] = (byte)(255 - data[i]); } streamWrite.Write(data, 0, length); } while (length == data.Length); //如果實際寫入長度等於我們設定的長度,有兩種情況1.文件正好是我們設定的長度2.文件超大只上傳了截取的一部分 } } } } } #endregion