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();
                }