我的代码出了什么问题? Vb.net [英] What's wrong with my code? Vb.net

查看:70
本文介绍了我的代码出了什么问题? Vb.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我很困惑我有这个代码:



hi everyone im so confused i have this code :

Dim LimitReached As Boolean = Me.InvokeIfRequired(Function() ProgressBar1.Value = ProgressBar1.Maximum)

'Keep looping until limit is reached.
While Not LimitReached

    'InvokeIfRequired() can take multiple lines.
    Me.InvokeIfRequired(
    Sub()
        ProgressBar1.Maximum = ListBox1.Items.Count.ToString() 'Calling ToString() is much better than Conversions.ToString().
        total.Text = ListBox1.Items.Count.ToString()
    End Sub) 'End of InvokeIfRequired().

    'Check if the limit is reached.
    LimitReached = Me.InvokeIfRequired(Function() ProgressBar1.Value = ProgressBar1.Maximum)

    If Not LimitReached Then

        Me.InvokeIfRequired(
        Sub()
            Try
                ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
                Label1.Text = ListBox1.SelectedItem.ToString
            Catch ex As Exception
            End Try
        End Sub)

        Try

            Me.InvokeIfRequired(
        Sub()
            ProgressBar1.Increment(1)
            detected.Text = Quarantine.ListBox2.Items.Count.ToString() 'Again, use .ToString(), not Conversions.ToString().
            Label5.Text = String.Format("{0:F2}%", ((ProgressBar1.Value / ProgressBar1.Maximum) * 100))
            files.Text = ProgressBar1.Value.ToString()
        End Sub)


            Dim SHA256 As New SHA256CryptoServiceProvider 'Shortened to "As New" instead of "As ... = New ..."

            'IMPORTANT: Wrap all streams in "Using .../End Using". This will ensure that the stream is closed and the file handle is released.
            Using f As New FileStream(ListBox1.SelectedItem, FileMode.Open, FileAccess.Read, FileShare.Read, 8192) 'Again, shortened to "As New".

                'REMOVED: You were setting "f = New FileStream..." two times. Not a good thing to do.
                SHA256.ComputeHash(f)
                Dim hash As Byte() = SHA256.Hash
                Dim buff As New StringBuilder '"As New".
                'This line is irrelevant: "Dim hashByte As Byte".
                For Each hashByte As Byte In hash
                    buff.Append(String.Format("{0:X2}", hashByte))
                Next


                Dim MyFilesList As String() = Directory.GetFiles(Application.StartupPath & "\Database\Sigs\Sha1\", "*.txt")
                Dim FoundedSearch As New List(Of String)()
                For Each filename As String In MyFilesList
                    Dim textFile As String = File.ReadAllText(filename)
                    If textFile.Contains(buff.ToString) Then
                        Me.InvokeIfRequired(Sub() f.Dispose())
                        Me.InvokeIfRequired(Sub() EncryptFile())
                        Me.InvokeIfRequired(Sub() Quarantine.ListBox2.Items.Add(ListBox1.SelectedItem()))
                        Me.InvokeIfRequired(Sub() WriteToLog("File Quarantined:" + ListBox1.SelectedItem))
                    End If
                Next

            End Using 'Close the FileStream.

        Catch ex As Exception
        End Try
    Else
        'REMOVED: "Timer1.Stop()" is no longer needed.

        Me.InvokeIfRequired(
        Sub()
            If CheckBox1.Checked = True Then
                System.Diagnostics.Process.Start("shutdown", "-s -t 00")
            Else
                ProgressBar1.Value = 0
                If ListBox1.Items.Count = 0 Then
                    If Form1.CheckBox1.Checked = True Then
                        full.CancelAsync()
                        quick.CancelAsync()
                        Critical.CancelAsync()
                        cust.CancelAsync()
                    End If
                Else
                    Form1.CheckBox1.Checked = False
                    Form1.CheckBox2.Checked = False
                    Form1.CheckBox3.Checked = False
                    Form1.CheckBox4.Checked = False
                    Quarantine.Label3.ForeColor = Color.DarkRed
                    Quarantine.Label2.ForeColor = Color.DarkRed
                    full.CancelAsync()
                    quick.CancelAsync()
                    Critical.CancelAsync()
                    cust.CancelAsync()

                End If
            End If
        End Sub) 'End of InvokeIfRequired().
    End If
    'Do some more background stuff...
End While







And

Dim SHA256 As New SHA256CryptoServiceProvider

是md5,它工作并扫描了md5哈希的列表,但现在我想做sha256,我使用sha256 hahses列表,它没有检测到文件(该文件是相同的哈希我检查使用病毒总数)



我尝试过:



as你可以看到上面我已经尝试将它改为sha256我唯一需要改变的东西但是没有工作。 : - (

was md5 and it worked and scanned a list of md5 hashes but now i want to do sha256 and i used a list of sha256 hahses and it doesnt detect the file(the file is the same hash i checked using virus total)

What I have tried:

as you can see above i've tried changing it to sha256 the only thing i should need to change but nope not working. :-(

推荐答案

嗯....是的,这个代码的一切都有问题。我不是想要粗鲁,但是你发布的内容很好有人来到你身后维持的东西的例子会燃烧到地面并从头开始重写。



方法应该做一件事,做一件事是短暂的代码量。你必须经过大量的废话只是为了切换哈希算法。这很糟糕。



你应该有一个方法只需要一个文件路径并返回一个字节数组,哈希结果。这样,它很容易更改哈希算法,所有这些都在一个地方完成。



我已经完成了类似的东西,但我写了一个包装文件路径的类,并公开了几个为该文件生成多个哈希的方法。恰好它会为文件生成MD5和SHA1哈希。这样的事情, (当然,这是C#。我是太懒了把它转换成VB.NET):

Ummm....yeah, EVERYTHING is wrong with that code. I'm not trying to be rude, but what you posted is a fine example of something that someone coming in behind you to maintain would burn to the ground and rewrite from scratch.

Methods should do one thing and do that one thing is a short amount of code. You have to go through a ton of crap just to switch out the hashing algorithm. That's bad.

You should have a method that just takes a filepath and returns a byte array, the hash result. That way, its easy to change out the hashing algorithm and it's all done in a single place.

I've done something similar, but I've written a class that wraps a filepath and exposes a couple of methods that generates multiple hashes for that file. It just so happens that it generates both an MD5 and an SHA1 hash for the file. Something like this, (of course, this is C#. I'm too lazy to convert it to VB.NET):
public class FileHash
{
    public string Filepath { get; private set; }

    public string Filename
    {
        get
        {
            return Path.GetFileName(Filepath);
        }
    }

    public byte[] MD5Hash { get; private set; }

    public byte[] SHA1Hash { get; private set; }

    private FileHash()
    {
    }

    public FileHash(string filepath)
    {
        if (string.IsNullOrWhiteSpace(filepath))
        {
            throw new ArgumentNullException(nameof(filepath));
        }

        Filepath = filepath;
    }

    public void ComputeHashes()
    {
        using (MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider())
        {
            MD5Hash = GenerateHash(md5Provider, Filepath);
        }

        using (SHA1CryptoServiceProvider sha1Provider = new SHA1CryptoServiceProvider())
        {
            SHA1Hash = GenerateHash(sha1Provider, Filepath);
        }
    }

    private byte[] GenerateHash(HashAlgorithm cryptoProvider, string filepath)
    {
        // Check the input parameters to make sure we get
        // something useful.
        if (cryptoProvider == null)
        {
            throw new ArgumentNullException(nameof(cryptoProvider));
        }

        if (string.IsNullOrWhiteSpace(filepath) || !File.Exists(filepath))
        {
            throw new ArgumentNullException(nameof(filepath));
        }

        // We need something to hold the results we
        // get back from the alsogirthm.
        byte[] result;

        // Open the file and hash it using the provided
        // algorithm.
        using (FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            result = cryptoProvider.ComputeHash(stream);
        }

        // Return the result.
        return result;
    }
}



这是该类的精简版。为清楚起见,我删除了所有异步内容。


This is the stripped down version of the class. I removed all the Async stuff for clarity.


这篇关于我的代码出了什么问题? Vb.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆