Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当两次运行写入本地存储的异步函数时,访问被拒绝_C#_Asynchronous_Windows Phone 8 - Fatal编程技术网

C# 当两次运行写入本地存储的异步函数时,访问被拒绝

C# 当两次运行写入本地存储的异步函数时,访问被拒绝,c#,asynchronous,windows-phone-8,C#,Asynchronous,Windows Phone 8,我有一个C#项目,其中包含针对web服务的服务引用 我有以下代码,首先在服务请求时触发一个方法: private void Button_Click(object sender, RoutedEventArgs e) { App.service.getFileCompleted += service_getFileCompleted; App.service.getFileAsync(App.user, App.document); } 而服务_getFileComp

我有一个C#项目,其中包含针对web服务的服务引用

我有以下代码,首先在服务请求时触发一个方法:

 private void Button_Click(object sender, RoutedEventArgs e)
 {
     App.service.getFileCompleted += service_getFileCompleted;
     App.service.getFileAsync(App.user, App.document);
 }
服务_getFileCompleted
应该检索
字节[]
,将其放入一个文件中,然后使用默认应用程序打开该文件:

 async void service_getFileCompleted(object sender, BackendReference.getFileCompletedEventArgs e)
 {
            string tmp = "temp." + e.Result.type;

            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile localFile = await local.CreateFileAsync(tmp, CreationCollisionOption.ReplaceExisting);

            using (Stream writeStream = await localFile.OpenStreamForWriteAsync())
            {
                writeStream.Seek(0, SeekOrigin.End);
                await writeStream.WriteAsync(e.Result.fileData, 0, e.Result.fileData.Length);
            }

            await Windows.System.Launcher.LaunchFileAsync(localFile);

        }
 }
应用程序第一次启动时,按钮被触发,它就像一个符咒。但是,当第二次按下按钮时,该行

Stream writeStream = await localFile.OpenStreamForWriteAsync()
强制转换
系统。UnauthorizedAccessException

更确切地说:

System.UnauthorizedAccessException:访问被拒绝。(来自HRESULT的异常:0x80070005(E_ACCESSDENIED))
在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中运行
在System.IO.WindowsRuntimeStorageExtensions.d_u5.MoveNext()中

---来自引发异常的上一个位置的堆栈结束跟踪---

在System.IO.WindowsRuntimeStorageExtensions.d_u5.MoveNext()中

---来自引发异常的上一个位置的堆栈结束跟踪---

在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中运行
在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
在archive.DocumentDetail.d__0.MoveNext()}System.Exception{System.UnauthorizedAccessException}

为什么会这样


谢谢

您正在启动该文件-可能应用程序仍然打开该文件,并且您正在尝试覆盖它…正如Jon所说,很可能在您第二次尝试按下按钮时该文件正在使用中。如果您使用一些变量,例如文件名的DateTime.Now.Ticks,则可以非常简单地解决此问题。这样,每次单击按钮时,名称都不同,因此不会启动UnauthorizedAccessException。