話不多說,請看代碼:
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
|
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 |
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!
原文鏈接:http://www.cnblogs.com/xcyg/archive/2016/12/25/6220550.html