File.OpenRead上的System.UnauthorizedAccessException

时间:2015-04-21 17:12:01

标签: c# silverlight windows-phone-8.1

我正在制作Windows Phone 8.1 Silverlight,当我尝试读取文件时,在阅读时会出现以下错误:

  

类型' System.UnauthorizedAccessException'的例外情况发生在   mscorlib.ni.dll但未在用户代码中处理

     

其他信息:访问路径   ' C:\ Data \ Users \ Public \ Pictures \ Camera Roll \ WP_20150421_001.jpg'是   拒绝。

{
    string filepath = FilePathTextBox.Text;
    string cryptPath = filepath;
    File.SetAttributes(cryptPath, System.IO.FileAttributes.Normal);

    FileStream stream = File.OpenRead(cryptPath);
    byte[] fileBytes = new byte[stream.Length];

    stream.Read(fileBytes, 0, fileBytes.Length);
    stream.Close();

    byte[] ProtectedFileBytes = ProtectedData.Protect(fileBytes, null);
    using (Stream file = File.OpenWrite(@"C:\Data\Users\Public\Documents"))
    {
        file.Write(ProtectedFileBytes, 0, ProtectedFileBytes.Length);
    }
    MessageBox.Show("File Sucessfully Encrypted");
}

所有相关的库都在清单中检查,我以管理员身份运行Visual Studio,我尝试过不同的文件,但都无济于事。

我添加了一个检查以验证文件是否存在,并且标记为false,但这可能是由于权限问题造成的。

有关解决此问题的任何建议吗?


编辑: 我现在有这个代码,它抛出一个System.ArgumentException:

private async void EncryptButton_Click(object sender, RoutedEventArgs e)
    {
        string filepath = FilePathTextBox.Text;
        string cryptPath = filepath;

        await FileOps();
            FileStream stream = File.OpenRead(cryptPath);
            byte[] fileBytes = new byte[stream.Length];

            stream.Read(fileBytes, 0, fileBytes.Length);
            stream.Close();

            byte[] ProtectedFileBytes = ProtectedData.Protect(fileBytes, null);
            using (Stream file = File.OpenWrite(@"C:\Data\Users\Public\Documents"))
            {
                file.Write(ProtectedFileBytes, 0, ProtectedFileBytes.Length);
            }
            MessageBox.Show("File Sucessfully Encrypted");
    }

    private async Task FileOps()
    {
        string filepath = FilePathTextBox.Text;
        string cryptPath = filepath;
        StorageFolder storageFolder = KnownFolders.CameraRoll;
        StorageFile file = await storageFolder.CreateFileAsync(cryptPath, CreationCollisionOption.ReplaceExisting);
    }

1 个答案:

答案 0 :(得分:1)

我认为这里的问题是你不能简单地通过路径访问...你需要浏览已知的文件夹:

KnownFolders class

Quickstart: Working with files and folders in Windows Phone 8

// Get the folder.
StorageFolder camera = Windows.Storage.KnownFolders.CameraRoll;

if (local != null)
{

    // Get the file.
    var file = await camera.OpenStreamForReadAsync("WP_20150421_001.jpg");

    // Read the data.
    using (StreamReader streamReader = new StreamReader(file))
    {
        //streamReader.ReadToEnd();
    }

}