码迷,mamicode.com
首页 > Windows程序 > 详细

C#强力粉碎文件代码分享

时间:2015-06-05 06:05:51      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

类似360的文件粉碎机

  7 using System;
  8 using System.Collections.Generic;
  9 using System.ComponentModel;
 10 using System.Data;
 11 using System.Drawing;
 12 using System.Linq;
 13 using System.Text;
 14 using System.Windows.Forms;
 15 using System.IO;
 16 using System.Runtime.InteropServices;
 17 using System.Text.RegularExpressions;
 18 using System.Diagnostics;
 19 
 20 
 21 namespace FileKiller
 22 {
 23 
 24     public partial class frmMain : Form
 25     {
 26         public const int iBufferLength = 1024000; // Declare 1Mb buffer.
 27 
 28         public frmMain()
 29         {
 30             InitializeComponent();
 31         }
 32 
 33         private void button_Quit_Click(object sender, EventArgs e)
 34         {
 35             Application.Exit();
 36         }
 37 
 38         private void button_Select_Click(object sender, EventArgs e)
 39         {
 40             if (openFileDialog1.ShowDialog() == DialogResult.OK)
 41             {
 42                 insertSelectedFilesIntoArray();
 43             }
 44         }
 45 
 46         private void insertSelectedFilesIntoArray()
 47         {
 48             string filename;
 49             bool bFileAlreadyExistInGrid = false;
 50 
 51             for (int i = 0; i < openFileDialog1.FileNames.Length; i++)
 52             {
 53                 bFileAlreadyExistInGrid = false;
 54                 filename = openFileDialog1.FileNames[i];
 55 
 56                 // Insert it into the Grid if not exist.
 57                 for (int j = 0; j < dataGridView1.Rows.Count; j++)
 58                 {
 59                     if (filename == (string)dataGridView1.Rows[j].Cells[0].Value)
 60                     {
 61                         bFileAlreadyExistInGrid = true;
 62                         break;
 63                     }
 64                 }
 65                 if (bFileAlreadyExistInGrid)
 66                     continue;
 67 
 68                 dataGridView1.Rows.Add(openFileDialog1.FileNames[i]);
 69             }
 70 
 71              updateStatusLine();
 72         }
 73 
 74         private void button_ClearGrid_Click(object sender, EventArgs e)
 75         {
 76             dataGridView1.Rows.Clear();
 77             updateStatusLine();       
 78         }
 79 
 80         private void Button_KillFiles_Click(object sender, EventArgs e)
 81         {
 82             if (dataGridView1.Rows.Count == 0)
 83             {
 84                 MessageBox.Show("尚未选择任何文件","提示!");
 85             }
 86             else if (MessageBox.Show("确定要强制删除选中的文件 ?", 
 87                                 "强制删除",
 88                   MessageBoxButtons.YesNo, MessageBoxIcon.Question)
 89                   == DialogResult.Yes)
 90             {
 91                 killTheFiles();
 92             }
 93         }
 94 
 95         private void killTheFiles()
 96         {
 97             int i = 0;
 98                 
 99             while (i < dataGridView1.Rows.Count)
100             {
101                 string filename = (string)dataGridView1.Rows[i].Cells[0].Value;
102                 if (killFile(filename))
103                     dataGridView1.Rows.RemoveAt(i);
104                 else
105                     i++;
106 
107             }
108         }
109 
110         private void updateStatusLine()
111         {
112             label_NumOfFiles.Text = dataGridView1.Rows.Count.ToString();
113         }
114 
115         private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
116         {
117             updateStatusLine();
118         }
119 
120         private bool killFile(string filename)
121         {
122             bool ret = true;
123             try
124             {
125                 byte[] rowDataBuffer;
126 
127                 // I open a stream w/o the fileshare flag defined. This declines sharing of the current file. 
128                 // Any request to open the file (by this process or another process) will fail until 
129                 // the file is closed.
130                 using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite))
131                 {
132 
133                     Cursor.Current = Cursors.WaitCursor;
134 
135                     FileInfo f = new FileInfo(filename);
136                     long count = f.Length;
137                     long offset = 0;
138                     rowDataBuffer = new byte[iBufferLength];
139                     while (count >= 0)
140                     {
141                         int iNumOfDataRead = stream.Read(rowDataBuffer, 0, iBufferLength);
142                         // I have inside the rowDataBuffer array the contents of a fragment of the file.
143                         if (iNumOfDataRead == 0)
144                         {
145                             break;
146                         }
147                         // I will apply the transformations to the rowDataBuffer array and then i will 
148                         // write it back to the file.
149                         if (radioButton_RandomData.Checked)
150                         {
151                             Random randombyte = new Random();
152                             randombyte.NextBytes(rowDataBuffer);
153                         }
154                         else if (radioButton_Blanks.Checked)
155                         {
156                             for (int i = 0; i < iNumOfDataRead; i++)
157                                 rowDataBuffer[i] = 0;
158                         }
159                         else
160                         {
161                             for (int i = 0; i < iNumOfDataRead; i++)
162                                 rowDataBuffer[i] = Convert.ToByte(Convert.ToChar(Convert.ToInt32(numericUpDown2.Value)));
163                         }
164                         // Write the new contents back to the file.
165                         for (int i = 0; i < numericUpDown1.Value; i++)
166                         {
167                             stream.Seek(offset, SeekOrigin.Begin);
168                             stream.Write(rowDataBuffer, 0, iNumOfDataRead);
169                         }
170 
171                         // Calculate the new offset & count
172                         offset += iNumOfDataRead;
173                         count -= iNumOfDataRead;
174                     } //while
175                 } // using
176 
177                 // Substitude every filename character with random numbers from 0 to 9.
178                 string newName = "";
179                 do
180                 {
181                     Random random = new Random();
182                     string cleanName = Path.GetFileName(filename);
183                     string dirName = Path.GetDirectoryName(filename);
184 
185                     int iMoreRandomLetters = random.Next(9);
186                     // for more security, don‘t use only the size of the original filename but add some random letter.
187                     for (int i = 0; i < cleanName.Length + iMoreRandomLetters; i++)
188                     {
189                         newName += random.Next(9).ToString();
190                     }
191                     newName = dirName + "\\" + newName;
192                 } while (File.Exists(newName));
193 
194                 //Rename the file to the new random name.
195                 File.Move(filename, newName);
196 
197                 //Delete the file now.
198                 File.Delete(newName);
199 
200             }
201             catch 
202             {
203                 //可能其他原因删除失败了,使用我们自己的方法强制删除
204                 try
205                 {
206                     string fileName = filename;//要检查被那个进程占用的文件
207                     Process tool = new Process();
208                     tool.StartInfo.FileName = "handle.exe";
209                     tool.StartInfo.Arguments = fileName + " /accepteula";
210                     tool.StartInfo.UseShellExecute = false;
211                     tool.StartInfo.RedirectStandardOutput = true;
212                     tool.Start();
213                     tool.WaitForExit();
214                     string outputTool = tool.StandardOutput.ReadToEnd();
215                     string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
216                     foreach (Match match in Regex.Matches(outputTool, matchPattern))
217                     {
218                        
219                         //结束掉所有正在使用这个文件的程序
220                         Process.GetProcessById(int.Parse(match.Value)).Kill();
221                     }
222                     System.IO.File.Delete(fileName);
223                     ret = true;
224                 }
225                 catch
226                 {
227                     ret = false;
228                 }
229             }
230             finally
231             {
232                 Cursor.Current = Cursors.Default;
233             }
234 
235             return ret;
236         }
237 
238 
239         private void button1_Click(object sender, EventArgs e)
240         {
241             System.Diagnostics.Process.Start("http://www.hellocsharp.com");
242         }
243 
244         private void numericUpDown2_ValueChanged(object sender, EventArgs e)
245         {
246             label_letter.Text = Convert.ToChar(Convert.ToInt32(numericUpDown2.Value)).ToString();
247         }
248 
249         private void radioButton_ASCII_CheckedChanged(object sender, EventArgs e)
250         {
251             numericUpDown2.Enabled = radioButton_ASCII.Checked;
252             label_letter.Enabled = radioButton_ASCII.Checked;
253         }
254 
255     }
256 }

 

C#强力粉碎文件代码分享

标签:

原文地址:http://www.cnblogs.com/wohexiaocai/p/4553306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!