VirusTotal Uploaded File is Zero Bytes

Viewed 137

I'm trying to upload a file to VirusTotal using .Net Core.But the uploaded file size is Zero Bytes.Why does this happen?

[Route("api/[controller]")]
public class ScannerController : Controller
{   [HttpGet]         
    public async Task<VirusTotalNet.Results.FileReport> ScanAsync(string file_id)
    {
        file_id = "./wwwroot/Upload/node-v12.14.1-x64.msi";
        VirusTotal virusTotal = new VirusTotal("");
        // virusTotal.UseTLS = true;         
        FileStream stream = System.IO.File.OpenRead(file_id);
        byte[] fileBytes = new byte[stream.Length];
        stream.Read(fileBytes, 0, fileBytes.Length);

        VirusTotalNet.Results.FileReport report = await virusTotal.GetFileReportAsync(stream);

        return report;
    }
}
1 Answers

You've read the entire file into a byte[] and there's an overload of GetFileReportAsync that will take that, so change the parameter from stream to fileBytes:

VirusTotalNet.Results.FileReport report = await virusTotal.GetFileReportAsync(fileBytes);

Derviş Kayımbaşıoğlu suggested resetting the stream's position but it turns out that the location mentioned was incorrect. Either of these:

stream.Seek(0L, SeekOrigin.Begin);

// or

stream.Position = 0L;

Needed to be done immediately before calling GetFileReportAsync, after the file had been read, not before. That would've worked.

But wait, there's more!

There's no need to read the file into fileBytes, which means there's no need to reset the position. The stream can be opened and passed directly to GetFileReportAsync. Including proper resource disposal, the entire method becomes this:

[HttpGet]         
public async Task<VirusTotalNet.Results.FileReport> ScanAsync(string file_id)
{
    file_id = "./wwwroot/Upload/node-v12.14.1-x64.msi";
    VirusTotal virusTotal = new VirusTotal("");
    // virusTotal.UseTLS = true;      

    using (FileStream stream = System.IO.File.OpenRead(file_id))
    {
        VirusTotalNet.Results.FileReport report = await virusTotal.GetFileReportAsync(stream);

        return report;
    }
}

This allows both the file to be read and the socket to be written asynchronously, and the data can be buffered in small amounts so that large files don't have to be loaded entirely into memory.

Related