【问题标题】:Warning Variable 'csCryptoStream' is used before it has been assigned a value. A null reference exception could result at runtime警告变量“csCryptoStream”在被赋值之前被使用。运行时可能会导致空引用异常
【发布时间】:2017-03-13 19:32:08
【问题描述】:

我是 VB.Net 的新手。我正在尝试调试我的项目,但收到警告:变量“csCryptoStream”在被赋值之前已被使用。运行时可能会导致空引用异常

我该如何解决?

Private Sub EncryptOrDecryptFile(strInputFile As String, strOutputFile As String, bytKey As Byte(), bytIV As Byte(), Direction As crypt.CryptoAction)
    ' The following expression was wrapped in a checked-statement
    Try
        Me.fsInput = New FileStream(strInputFile, FileMode.Open, FileAccess.Read)
        Me.fsOutput = New FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write)
        Me.fsOutput.SetLength(0L)
        Dim bytBuffer As Byte() = New Byte(4096) {}
        Dim lngBytesProcessed As Long = 0L
        Dim lngFileLength As Long = Me.fsInput.Length
        Dim cspRijndael As RijndaelManaged = New RijndaelManaged()
        Me.pbStatus.Value = 0
        Me.pbStatus.Maximum = 100
        Dim csCryptoStream As CryptoStream
        Select Case Direction
            Case crypt.CryptoAction.ActionEncrypt
                csCryptoStream = New CryptoStream(Me.fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write)
            Case crypt.CryptoAction.ActionDecrypt
                csCryptoStream = New CryptoStream(Me.fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV), CryptoStreamMode.Write)
        End Select
        While lngBytesProcessed < lngFileLength
            Dim intBytesInCurrentBlock As Integer = Me.fsInput.Read(bytBuffer, 0, 4096)

Warning --->     csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)
            ' The following expression was wrapped in a unchecked-expression
            lngBytesProcessed += CLng(intBytesInCurrentBlock)
            ' The following expression was wrapped in a unchecked-expression
            Me.pbStatus.Value = CInt(Math.Round(CDec(lngBytesProcessed) / CDec(lngFileLength) * 100.0))
        End While

【问题讨论】:

  • 在使用之前先给它赋值可能是显而易见的事情……

标签: vb.net encryption filestream


【解决方案1】:
  1. 如下声明CryptoStream

     Dim csCryptoStream As CryptoStream = Nothing
    
  2. Case/Select 中添加“Case Else”子句

  3. 在使用此变量之前检查是否

    If Not IsNothing(csCryptoStream)
      '    ....
    End If
    

【讨论】:

  • 我在尝试调试时遇到其他错误:Microsoft.VisualBasic.dll 中发生了“Microsoft.VisualBasic.ApplicationServices.NoStartupFormException”类型的未处理异常
  • @MuhammadFathan 如果您在该行收到错误,请尝试将其声明为“新”,即 Dim csCryptoStream As New CryptoStream
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
相关资源
最近更新 更多