XYZT
XYZT

Reputation: 43

Can't read from newly created file with content

i am struggling with getting SHA256 sum of a file.
When program starts method GetSHA256FromStream is called.
The error occurs in method GetSHA256 when File.Open is called.
I am running Visual Studio as Administrator.

ERROR:

System.IO.IOException: 'The process cannot access the file
'C:\Users\WS1\AppData\Local\Temp\test.ttttt'
because it is being used by another process.'

I don't really know if i need to use async/await for working with files.

    public static string GetSHA256FromStream(Stream s)
    {
        string _tpath = Helper.GetTEMPPath("test.ttttt"); // %TEMP%\\test.ttttt
        Helper.WriteStreamToFile(s, _tpath);
        return Checksum.GetSHA256(_tpath, true);
    }

    public async static void WriteStreamToFile(Stream s, string outpath)
    {
        try
        {
            FileStream fStream = File.Open(outpath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
            s.Seek(0, SeekOrigin.Begin);
            await s.CopyToAsync(fStream);
            fStream.Close();
        }
        catch (Exception e)
        {
            return;
        }
    }

    public static string GetSHA256(string text, bool isFile = false)
    {
        SHA256 sha256 = SHA256.Create();
        byte[] hash;
        if (isFile)
        {
            FileStream stream = File.OpenRead(text);
            hash = sha256.ComputeHash(stream);
        }
        else
        {
            byte[] textBytes = Encoding.Default.GetBytes(text);
            hash = sha256.ComputeHash(textBytes);
        }
        return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
    }

Upvotes: 0

Views: 112

Answers (1)

derpirscher
derpirscher

Reputation: 17382

The method WriteStreamToFile is async, but you are not awaiting it in GetSHA256FromStream. Thus, you are already calling GetSHA256() and trying to open the file, while WriteStreamToFile is still writing.

You could for instance make GetSHA256FromStream also async and then await writing to the file and then once that task is finished calculate the checksum

BTW, you should not return void on async methods but a Task

public static async Task<string> GetSHA256FromStream(Stream s)
{
    try {
        string _tpath = Helper.GetTEMPPath("test.ttttt"); // %TEMP%\\test.ttttt
        await Helper.WriteStreamToFile(s, _tpath);
        return Checksum.GetSHA256(_tpath, true);
    } 
    catch (Exception e) {
        //some error logging
    } 
}

public async static Task WriteStreamToFile(Stream s, string outpath)
{
    try
    {
        FileStream fStream = File.Open(outpath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
        s.Seek(0, SeekOrigin.Begin);
        await s.CopyToAsync(fStream);
        fStream.Close();
    }
    catch (Exception e)
    {
        //Don't use empty catches but log some error here
    }
}

Upvotes: 2

Related Questions