08實現文件和文件夾的復制,08實現文件夾
private void btnSave_Click(object sender, EventArgs e) //文件復制、保存方法
{
#region 靜態復制文件(寫死)
string desPath = @"c:\1\1.chm";
if (File.Exists(desPath))
{
//目標文件已存在
if (MessageBox.Show(("文件已存在,是否覆蓋"), "詢問", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes) //選擇Yes 確定覆蓋
{
//復制文件
File.Copy(@"c:\ls\w3.chm", desPath, true);
MessageBox.Show("覆蓋成功");
}
}
else //文件不存在
{
//開始復制
File.Copy(@"c:\ls\w3.chm", desPath, true);
MessageBox.Show("復制成功");
}
//顯示打開對話框,返回值為dialogResult類型,如果是OK,則用戶點擊的為打開,否則為取消
openFileDialog1.InitialDirectory=(@"c:\1"); //選擇文件時的默認位置
//openfilediaglog1.filter中的fileter是過濾器的作用
//showdialog()顯示對話框的方法.
openFileDialog1.Filter = "可執行程序|*.exe|TXT文本|*.txt|圖片文件|*.jpg|所有文件|*.*";//可保存類型
if (openFileDialog1.ShowDialog() == DialogResult.OK)//點擊了打開
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK) //說明點yes 也就是確認保存
{
File.Copy(openFileDialog1.FileName, saveFileDialog1.FileName, true);
MessageBox.Show("保存完成");
}
}
#endregion
}
//File類是對文件操作的,包括復制、保存、創建時間、修改時間等等等等。
//Directory功能類似file
#region 動態
private void btnCopyContents_Click(object sender, EventArgs e)
{
string oldDir, newDir; //分別是原文件夾和目標文件夾
FolderBrowserDialog sourceFolder = new FolderBrowserDialog();//動態生成了folderbrowserdialog這個控件 不需要拖控件
sourceFolder.Description = "請選擇要復制的文件夾";//顯示了一個簡單說明
if(sourceFolder.ShowDialog()==DialogResult.OK)//點了確定
{
oldDir = sourceFolder.SelectedPath;
sourceFolder.Description = "請選擇要復制到的文件夾";//修改了一下sourcefolder的說明文字 便於使用者使用
if (sourceFolder.ShowDialog()== DialogResult.OK) //如果確定 那麼執行下面代碼塊代碼
{
newDir = sourceFolder.SelectedPath;
//獲取當前要復制的文件夾中的所有文件(注意!不包含下級文件夾及其中的文件)
string[] files = Directory.GetFiles(oldDir);//定義了個字符數組來接收源文件內需要復制的文件
foreach (string filepath in files) //也可以用for語句
{
//File.Copy(filepath,newDir+"\\"+filepath.Substring(filepath.LastIndexOf("\\")+1),true);
//拆分了一下,更為簡潔
string nFileName ; //定義一個string類型,來獲取文件名
nFileName = filepath.Substring(filepath.LastIndexOf("\\") + 1); //獲取要復制的文件夾裡的文件名
File.Copy(filepath, newDir + "\\" + nFileName, true); //最後得出要復制的文件夾以及文件夾裡的文件名並進行復制
}
//MessageBox.Show("復制完成");
}
//MessageBox.Show(sourceFolder.SelectedPath);
}
}
#endregion