使用MD5的C#防病毒程序-BackgroundWorker/FileNotFoundException-路径不正确

本文关键字:FileNotFoundException- 路径 不正确 -BackgroundWorker 防病毒程序 MD5 使用 | 更新日期: 2023-09-27 18:28:00

我正在尝试创建一个防病毒程序,该程序从文本文件中提取一组5个MD5哈希,在用户使用浏览选择文件夹并单击扫描后,该程序应该遍历所有文件,在后台工作人员中为每个文件运行哈希并进行比较,如果结果是检测到的病毒,则将结果输入到列表框中。

目前代码正在捕获(FileNotFoundException),并且显示FilePath的消息框正在生成"Path1"Path2"Path3",有人能解释我如何更正代码以正确馈送路径吗?我真的不明白"Path1"Path2"Path3"等等是从哪里来的?

以下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;    
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace TestAntivirus
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private int noofvirus = 0;
        List<string> completehashes = new List<string>();
    private void Browse_Click(object sender, EventArgs e)
    {
        folderBrowserDialog1.ShowDialog();
        label1.Text = folderBrowserDialog1.SelectedPath;
        noofvirus = 0;
        label2.Text = "Viruses:" + noofvirus.ToString();
        progressBar1.Value = 0;
        listBox1.Items.Clear();
    }
    private void BDone_Click(object sender, EventArgs e)
    {
        this.Close();
    }
    private void BScan_Click(object sender, EventArgs e)
    {
        string[] scanned = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
        int numofscanned = scanned.Count();
        progressBar1.Maximum = scanned.Length;
        foreach (string item in scanned)
        {
            for (int i = 0; i < (numofscanned); i++)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += new DoWorkEventHandler (backgroundWorker1_DoWork);
                worker.RunWorkerAsync(i);
            }              

        }
        foreach (string hashes in completehashes)
        {
            try
            {
                StreamReader stream = new StreamReader(hashes);
                string read = stream.ReadToEnd();
                var lineCount = File.ReadLines(@"C:'Users'Neil Bagley'Desktop'ProjectWork'VirusHashes'Test5.txt").Count();
                var virus = File.ReadAllLines(@"C:'Users'Neil Bagley'Desktop'ProjectWork'VirusHashes'Test5.txt");
                foreach (string st in virus)
                {
                    if (Regex.IsMatch(read, st))
                    {
                        MessageBox.Show("Virus Detected");
                        noofvirus += 1;
                        label2.Text = "Viruses: " + noofvirus.ToString();
                        listBox1.Items.Add(hashes);
                    }
                    progressBar1.Increment(1);
                }
            }
            catch
            {
                string read = hashes;
                var virus = File.ReadAllLines(@"C:'Users'Neil Bagley'Desktop'ProjectWork'VirusHashes'Test5.txt");
                foreach (string st in virus)
                {
                    if (Regex.IsMatch(read, st))
                    {
                        MessageBox.Show("Virus Detected");
                        noofvirus += 1;
                        label2.Text = "Viruses:" + noofvirus.ToString();
                        listBox1.Items.Add(hashes);
                    }
                }
            }
        }
    }
    private static String MakeHashString(byte[] hashbytes)
    {
        StringBuilder hash = new StringBuilder(32);
        foreach (byte b in hashbytes)
        {
            hash.Append(b.ToString("X2").ToLower());
        }
        return hash.ToString();
    }
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        string filePath = e.Argument.ToString();
        byte[] buffer;
        int bytesRead;
        long size;
        long totalBytesRead = 0;
        try
        {
            using (Stream file = File.OpenRead(filePath))
            {
                size = file.Length;
                using (HashAlgorithm hasher = MD5.Create())
                {
                    do
                    {
                        buffer = new byte[4096];
                        bytesRead = file.Read(buffer, 0, buffer.Length);
                        totalBytesRead += bytesRead;
                        hasher.TransformBlock(buffer, 0, bytesRead, null, 0);

                        backgroundWorker1.ReportProgress((int)((double)totalBytesRead / size * 100));

                    } while (bytesRead != 0);
                    hasher.TransformFinalBlock(buffer, 0, 0);
                    e.Result = MakeHashString(hasher.Hash);
                }
            }
        }
        catch (FileNotFoundException)
        {
            MessageBox.Show("File not found in the specified path" + filePath);
        }
        catch (IOException)
        {
            MessageBox.Show("IOException");
        }

    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    }
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        completehashes.Add(e.Result.ToString());
        progressBar1.Value = 0;
    }


    }
}

在之前给出的建议之后,我试图开始重新制作该项目,但我现在不确定为什么这只会在列表框中添加一个哈希,而不是像我所期望的那样添加"foreach(扫描中的字符串扫描)",有人能解释吗?新尝试:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace AntiVirus
{
    public partial class Form1 : Form
     {
        public Form1()
        {
            InitializeComponent();
        }
        private int noofvirus = 0;        
        private string[] scanned;
        private void BBrowse_Click(object sender, EventArgs e)
        {
        folderBrowserDialog1.ShowDialog();
        label1.Text = folderBrowserDialog1.SelectedPath;
        noofvirus = 0;
        label2.Text = "Viruses:" + noofvirus.ToString();
        progressBar1.Value = 0;            
        listBox1.Items.Clear();
        }
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        scanned = Directory.GetFiles(e.Argument.ToString(), "*.*", SearchOption.AllDirectories);

        foreach (string scan in scanned)
        {                
            byte[] buffer;
            int bytesRead;
            long size;
            long totalBytesRead = 0;
            using (Stream file = File.OpenRead(scan))
            {
                size = file.Length;
                using (HashAlgorithm hasher = MD5.Create())
                {
                    do
                    {
                        buffer = new byte[4096];
                        bytesRead = file.Read(buffer, 0, buffer.Length);
                        totalBytesRead += bytesRead;
                        hasher.TransformBlock(buffer, 0, bytesRead, null, 0);

                        backgroundWorker1.ReportProgress((int)((double)totalBytesRead / size * 100));

                    } while (bytesRead != 0);
                    hasher.TransformFinalBlock(buffer, 0, 0);
                    e.Result = MakeHashString(hasher.Hash);
                }
            }                
        }

    }
    private static String MakeHashString(byte[] hashbytes)
    {
        StringBuilder hash = new StringBuilder(32);
        foreach (byte b in hashbytes)
        {
            hash.Append(b.ToString("X2").ToLower());
        }
        return hash.ToString();
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    }
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        listBox1.Items.Add(e.Result.ToString());
        progressBar1.Value = 0;
    }
    private void BScan_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync(folderBrowserDialog1.SelectedPath);
    }
    private void BDone_Click(object sender, EventArgs e)
    {
        this.Close();
    }

   }
}

使用MD5的C#防病毒程序-BackgroundWorker/FileNotFoundException-路径不正确

您为每个哈希设置了e.Result,但只有当RunWorkerCompleted事件被激发时,它才会被添加到列表框中。(当DoWork事件完成时,该事件只触发一次,因此只添加最后一个散列)

当您获得如下文件哈希时,我建议使用backgroundWorker1.ReportProgress第二个参数userState
(注意,代码是未经测试的/psuedocode,但希望它能让你走上正轨)

//CalculateTotalProgress() is a fictional function returning total progress percentage
backgroundWorker1.ReportProgress(CalculateTotalProgress(currentFile,totalFiles), MakeHashString(hasher.Hash));

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    listBox1.Items.Add(e.UserState.ToString);
    progressBar1.Value = e.ProgressPercentage;
}
相关文章:
  • 没有找到相关文章