Posted on 2 Comments

UnauthorizedAccessException C# File.IO Async

I had to upgrade one application and put some extra functionality. So i added an async function that handles a .txt file and edit some fields.

So i used this code

StorageFolder storageFolder = ApplicationData.Current.RoamingFolder;
 storageFile = await storageFolder.CreateFileAsync("file.txt",CreationCollisionOption.ReplaceExisting);
await FileIO.AppendTextAsync(storageFile, "saveSomeText");

 

But i also had a function in MainPage that asynchronously was reading the same file

StorageFolder storageFolder = ApplicationData.Current.RoamingFolder;
StorageFile storageFile;
storageFile = await storageFolder.CreateFileAsync("file.txt",CreationCollisionOption.OpenIfExists);
IList<string> list = await FileIO.ReadLinesAsync(storageFile);

 

Both functions were async so we could not determine when each function was running and which will be executed first.

So when i tried to run the app i came across with UnauthorizedAccessException because both function maybe were trying to access the file the same time. So i have to make one function wait. You can achieve that by many ways. I used the below function.

 

            async void waitsomething()
            {
                await Task.Delay(2000);
            }

 

But i want to execute this code only once. So i used localSettings

                try
                {
                    tempstr = App.localSettings.Values["YOURkey"].ToString();
                }
                catch (NullReferenceException exmas)
                {
                    waitsomething();
                }

 

 

2 thoughts on “UnauthorizedAccessException C# File.IO Async

  1. This is a bad hacky workaround. If you have code accessing a file in multiple spots and especially in multiple threads you should be using a lock around the code accessing the file so that the other file can’t access at the same time.

    1. Yes, that’s the right way to do this, but i had to run 2 async operations on startup and that way worked as well

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.