C#对本地文件简单(删除/修改)操作

前段时间一日本华侨朋友,要我帮他写个对本地文件的简单操作,今天在这里和大家分享一下,如有什么地方不足,请大赐教……

(读取的是本地F盘下e文件夹中所有txt文件)运行效果图如下所示:

重命名操作运行如下图所示:

当时做的时候,觉得难的是编辑怎么弹窗体去做,本人是做web开发的,对winform不是很熟悉,有什么不对的地方可以指教一下!

项目结构图如下所示:

Basic.cs源码如下所示:

Basic.cs
 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Sony
7 {
8 public class Basic
9 {
10 /// <summary>
11 /// 截取文件路径字符串
12 /// </summary>
13 /// <param name="str">str</param>
14 /// <returns></returns>
15 public static string SubStr(string str)
16 {
17 int length = str.LastIndexOf("\\");
18 string fileName = str.Substring(length);
19 string name = fileName.Substring(1, fileName.LastIndexOf(".") - 1);
20 return name;
21 }
22
23 /// <summary>
24 /// 判断一个文件是否正在使用函数
25 /// </summary>
26 /// <param name="fileName">将要判断文件的文件名</param>
27 /// <returns></returns>
28 public static bool IsFileInUse(string fileName)
29 {
30 bool inUse = true;
31 if (System.IO.File.Exists(fileName))
32 {
33 System.IO.FileStream fs = null;
34 try
35 {
36 fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
37 inUse = false;
38 }
39 catch (System.IO.IOException)
40 {
41 return true;
42 }
43 finally
44 {
45 if (fs != null)
46 {
47 fs.Close();
48 }
49 }
50 return inUse;
51 }
52 else
53 {
54 return false;
55 }
56 }
57 }
58 }

FolderDialog.cs代码如下所示:

FolderDialog.cs
 1 using System;
2 using System.Collections.Generic;
3 using System.Windows.Forms.Design;
4 using System.Text;
5 using System.Windows.Forms;
6
7 namespace Sony
8 {
9 public class FolderDialog : FolderNameEditor
10 {
11 FolderBrowser fDialog = new FolderBrowser();
12
13 public FolderDialog() { }
14
15 public DialogResult DisplayDialog()
16 {
17 return DisplayDialog("请选择一个文件夹");
18 }
19
20 public DialogResult DisplayDialog(string description)
21 {
22 fDialog.Description = description;
23 return fDialog.ShowDialog();
24 }
25
26 public string Path
27 {
28 get
29 {
30 return fDialog.DirectoryPath;
31 }
32 }
33
34 ~FolderDialog()
35 {
36 fDialog.Dispose();
37 }
38 }
39 }

edit.cs代码如下所示:

edit.cs
 1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Windows.Forms;
5
6 namespace Sony
7 {
8 public partial class edit : Form
9 {
10 private string path;
11 private string fileName;
12 private string type = ".txt";
13 public file_opear fo;
14 public edit()
15 {
16 InitializeComponent();
17 }
18
19 /// <summary>
20 /// 构造函数重载
21 /// </summary>
22 /// <param name="filePath"></param>
23 public edit(string filePath)
24 {
25 InitializeComponent();
26 this.txtFileName.Text = Basic.SubStr(filePath).Trim();
27 this.fileName = this.txtFileName.Text;
28 this.path = filePath.Substring(0, filePath.LastIndexOf("\\") + 1);
29 }
30
31 /// <summary>
32 /// 确定修改文件名称
33 /// </summary>
34 /// <param name="sender"></param>
35 /// <param name="e"></param>
36 private void btnOk_Click(object sender, EventArgs e)
37 {
38 if (fileName == this.txtFileName.Text.Trim())//没有修改文件名称
39 {
40 MessageBox.Show("新文件名和原文件名相同,不需要修改!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
41 this.Close();
42 }
43 else if (this.txtFileName.Text.Trim().Length < 1)//没有输入文件名
44 {
45 MessageBox.Show("请输入文件名称!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
46 }
47 else
48 {
49 string old_filePath = this.path + fileName + type;
50 string new_filePath = this.path + this.txtFileName.Text.Trim() + type;
51 if (System.IO.File.Exists(new_filePath))
52 {
53 MessageBox.Show("已经存在了一个" + new_filePath + "文件", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
54 }
55 else if (Basic.IsFileInUse(old_filePath))
56 {
57 MessageBox.Show("系统在尝试修改'正在使用'(" + old_filePath + ")文件名称时失败!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
58 }
59 else
60 {
61 System.IO.File.Move(old_filePath, new_filePath);
62 MessageBox.Show("文件名称修改成功!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
63 this.Close();
64 }
65 }
66 }
67
68 /// <summary>
69 /// 取消
70 /// </summary>
71 /// <param name="sender"></param>
72 /// <param name="e"></param>
73 private void btnCancel_Click(object sender, EventArgs e)
74 {
75 this.Close();
76 }
77 }
78 }

file_opear.cs代码如下所示:

file_opear.cs
 1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9
10 namespace Sony
11 {
12 public partial class file_opear : Form
13 {
14 private string path = @"F:\e";
15 private DataTable dt;
16 private List<string> files;//文件名 例如:hello
17 private List<string> files_path;//文件绝对路径 例如:F://aa//hello.csv
18 private string type = "*.txt";
19 public edit et;
20
21 /// <summary>
22 /// 构造函数
23 /// </summary>
24 public file_opear()
25 {
26 InitializeComponent();
27 }
28
29 /// <summary>
30 /// 窗体加载
31 /// </summary>
32 /// <param name="sender"></param>
33 /// <param name="e"></param>
34 private void file_opear_Load(object sender, EventArgs e)
35 {
36 this.initDT();
37 this.FillData(this.dataGridView1);
38 }
39
40 /// <summary>
41 /// 初始化DataTable
42 /// </summary>
43 private void initDT()
44 {
45 this.dt = new DataTable();
46 dt.Columns.Add("NO.", typeof(int));
47 dt.Columns.Add("ProgName", typeof(string));
48 }
49
50 /// <summary>
51 /// 选择文件并加载
52 /// </summary>
53 /// <param name="sender"></param>
54 /// <param name="e"></param>
55 private void selectFolder_Click(object sender, EventArgs e)
56 {
57 FolderDialog fDialog = new FolderDialog();
58 this.files = new List<string>();
59 fDialog.DisplayDialog();//无参数-对话框上默认说明文字,带一string类型参数-自定义说明文字
60 this.path = fDialog.Path;//选择的文件夹路径
61 if (!string.IsNullOrEmpty(path))
62 {
63 this.FillData(this.dataGridView1);
64 }
65 }
66
67 /// <summary>
68 /// 填充数据到DataGridView
69 /// </summary>
70 /// <param name="dataGridView">dataGridView</param>
71 public void FillData(DataGridView dataGridView)
72 {
73 this.GetAllFiles(this.path, this.type);
74 this.txtPath.Text = this.path;
75 if (this.files_path.Count > 0)
76 {
77 this.files = this.GetFileName(files_path);
78 this.dt.Clear();
79 for (int i = 0; i < files.Count; i++)
80 {
81 DataRow dr = this.dt.NewRow();
82 dr["NO."] = i + 1;
83 dr["ProgName"] = files[i];
84 this.dt.Rows.Add(dr);
85 }
86 dataGridView.DataSource = this.dt;
87 this.SetColumn(dataGridView);
88 }
89 else
90 {
91 MessageBox.Show("你选择的文件夹中还没有.txt文件", "提示");
92 }
93 }
94
95 /// <summary>
96 /// 在DataGridView指定位置中添加列和相应属性
97 /// </summary>
98 /// <param name="dataGridView">dataGridView</param>
99 private void SetColumn(DataGridView dataGridView)
100 {
101 dataGridView.AllowUserToAddRows = false;//禁止最后一行空行显示
102 //dataGridView.RowHeadersVisible = false;//隐藏最左边状态栏
103 //所有列居中并且禁止排序
104 for (int i = 0; i < dataGridView.Columns.Count; i++)
105 {
106 //dataGridView.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//内容居中
107 dataGridView.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;//禁止排序
108 }
109 dataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//表头居中
110 }
111
112 /// <summary>
113 /// 获取选择目录中匹配match的文件
114 /// </summary>
115 /// <param name="path">路径</param>
116 /// <param name="match">匹配</param>
117 private void GetAllFiles(string path, string match)
118 {
119 this.files_path = new List<string>();
120 try
121 {
122 string[] fs = System.IO.Directory.GetFiles(path, match);
123 files_path.AddRange(fs);
124 }
125 catch (Exception ex)
126 {
127 throw new Exception(ex.Message.ToString());
128 }
129 }
130
131 /// <summary>
132 /// 截取文件名
133 /// </summary>
134 /// <param name="files"></param>
135 /// <returns></returns>
136 private List<string> GetFileName(List<string> files)
137 {
138 List<string> fileName = new List<string>();
139 string name = string.Empty;
140 for (int i = 0; i < this.files_path.Count; i++)//遍历有所文件路径截取文件名称
141 {
142 fileName.Add(Basic.SubStr(files[i]));
143 }
144 return fileName;
145 }
146
147 /// <summary>
148 /// 鼠标单击单行时事件
149 /// </summary>
150 /// <param name="sender"></param>
151 /// <param name="e"></param>
152 private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
153 {
154 if (this.dataGridView1.Rows[e.RowIndex].Cells[0].ValueType == typeof(bool))
155 {
156 if (this.dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue.ToString().Equals("True"))
157 {
158 this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = false;
159 this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
160 }
161 else
162 {
163 this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = true;
164 this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.GreenYellow;
165 }
166 }
167 }
168
169 /// <summary>
170 /// 删除
171 /// </summary>
172 /// <param name="sender"></param>
173 /// <param name="e"></param>
174 private void btnDelete_Click(object sender, EventArgs e)
175 {
176 List<int> Selected = this.GetSelected(this.dataGridView1);//选择的索引
177 int i = 0;
178 DialogResult dr;
179 if (Selected.Count == 0)
180 {
181 MessageBox.Show("没有选择任何行", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
182 }
183 else
184 {
185 dr = MessageBox.Show("是否删除所选行,删除后无法恢复,是否继续?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
186 if (dr == DialogResult.Yes)
187 {
188 foreach (int index in Selected)
189 {
190 string file_path = this.files_path[index];//获取文件的绝对路径
191 if (Basic.IsFileInUse(file_path))//判断文件是否在使用
192 {
193 MessageBox.Show("已删除了" + i.ToString() + "个文件,系统在尝试删除'正在使用'(" + file_path + ")文件时失败!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
194 this.Close();
195 }
196 else
197 {
198 i++;
199 System.IO.File.Delete(file_path);
200 }
201 }
202 MessageBox.Show("成功删除了" + i.ToString() + "个文件!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
203 this.FillData(this.dataGridView1);
204 }
205 }
206 }
207
208 /// <summary>
209 /// 重命名
210 /// </summary>
211 /// <param name="sender"></param>
212 /// <param name="e"></param>
213 private void btnReName_Click(object sender, EventArgs e)
214 {
215 List<int> Selected = this.GetSelected(this.dataGridView1);//选择的索引
216 if (Selected.Count == 0)
217 {
218 MessageBox.Show("没有选择任何行", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
219 }
220 else if (Selected.Count > 1)
221 {
222 MessageBox.Show("只能选择一行进行编辑", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
223 }
224 else//编辑
225 {
226 string filePath = this.files_path[Selected[0]].ToString();
227 this.et = new edit(filePath);
228 this.et.fo = this;
229 et.ShowDialog();
230 this.FillData(this.dataGridView1);
231 }
232 }
233
234 /// <summary>
235 /// 获取选择行的索引号
236 /// </summary>
237 /// <param name="dataGridView">dataGridView</param>
238 /// <returns>索引List集</returns>
239 private List<int> GetSelected(DataGridView dataGridView)
240 {
241 List<int> Selected = new List<int>();
242 for (int i = 0; i < dataGridView.Rows.Count; i++)
243 {
244 if (dataGridView.Rows[i].Cells[0].FormattedValue.ToString() == "True")
245 {
246 Selected.Add(i);
247 }
248 }
249 return Selected;
250 }
251
252 /// <summary>
253 /// 关闭
254 /// </summary>
255 /// <param name="sender"></param>
256 /// <param name="e"></param>
257 private void btnClose_Click(object sender, EventArgs e)
258 {
259 this.Close();
260 }
261 }
262 }

设计器代码照着图拖控件就行,如果你觉得对你有意义,可以下载或者转载,如有不对的地方,请指示,不要喷,谢谢!

源码下载,点击这里

版权所有,转载请注明出处!

一切伟大的行动和思想,都有一个微不足道的开始。微不足道的我,正在吸取知识的土壤,希望能取得成功!不嫌弃我微不足道的,愿交天下好友!

posted @ 2011-10-06 15:43  xu_happy_you  阅读(6488)  评论(36编辑  收藏  举报