简体   繁体   中英

UWP FileStream throws "Access to path is denied."

I'm in college and I've been granted a task to make an app that calculates and shows the hash of a file in UWP application. Every time when I want to compute the hash of the file that I picked, I get "Access to path is denied." error. I want to compute the hash passing a filestream as a parameter. I've tried to run Visual Studio as administrator but with no success. Below is the code.

public partial class MainPage : Page
{
    byte[] result;
    string[] algorithms = { "MD5", "SHA-1", "SHA256", "SHA384", "SHA512" };
    string algorithm = "", path = "";
    HashAlgorithm hash;

    public MainPage()
    {
        this.InitializeComponent();

        AlgorithmsList.ItemsSource = algorithms;
    }

    /* Browse for file */
    private async void BrowseButton(object sender, RoutedEventArgs e)
    {
        FileOpenPicker openPicker = new FileOpenPicker();

        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        openPicker.FileTypeFilter.Add("*");

        StorageFile file = await openPicker.PickSingleFileAsync();

        if (file != null)
        {
            resultTextBlock.Text = "Result";
            pathTextBlock.Text = file.Path;
            path = file.Path;
        }
    }

    /* Method that shows the hash after computing it */
    private async void GoButton(object sender, RoutedEventArgs e)
    {
        if (path == "" || AlgorithmsList.SelectedIndex == -1)
        {
            MessageDialog dialog;

            if (path == "")
                dialog = new MessageDialog("You have to select a file");
            else
                dialog = new MessageDialog("You have to select an algorithm");

            await dialog.ShowAsync();
        }
        else
        {
            algorithm = AlgorithmsList.Text;
            string hash = await Task.Run(() => CalculateHash());
            resultTextBlock.Text = hash;
        }
    }

    private string CalculateHash()
    {
        string exception = "";

        hash = InitAlgorithm();

        try
        {
            using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                fileStream.Position = 0;
                result = hash.ComputeHash(fileStream);
            }

            StringBuilder sb = new StringBuilder(result.Length * 2);
            foreach (byte b in result)
            {
                sb.AppendFormat("{0:x2}", b);
            }

            return sb.ToString();
        }
        catch (Exception e)
        {
            exception = e.ToString();
        }

        return exception;
    }

    private HashAlgorithm InitAlgorithm()
    {
        HashAlgorithm hash = null;

        switch (algorithm)
        {
            case ("MD5"):
                hash = MD5.Create();
                break;
            case ("SHA-1"):
                hash = SHA1.Create();
                break;
            case ("SHA256"):
                hash = SHA256.Create();
                break;
            case ("SHA384"):
                hash = SHA384.Create();
                break;
            case ("SHA512"):
                hash = SHA512.Create();
                break;
        }

        return hash;
    }
}

You don't have access to that path. You have just access to StorageFile . So make it variable in MainPage and use it in CalculateHash .

Please don't use the path to directly create a FileStream , UWP applications have strict restrictions on accessing files through the path.

You have obtained the StorageFile object through FileOpenPicker , please use it instead of the path variable, and use the following code:

using (var stream = await file.OpenStreamForReadAsync())
{
    stream.Position = 0;
    result = hash.ComputeHash(stream);
}

StringBuilder sb = new StringBuilder(result.Length * 2);
foreach (byte b in result)
{
    sb.AppendFormat("{0:x2}", b);
}

return sb.ToString();

Best regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM