none
[UWP] File Write (WriteTextAsync) frequently throw exception. RRS feed

  • Question

  • I have implementing logging error message in a file in UWP. When calling the WriteTextAsync frequently, it throws exception as Access denied. The problem is there is no synchronization to do single write process. While writing first data content, second write call is occurred same time which is the reason for exception. Please help me to solve this issue.

    Following is the sample code referred from Windows Universal Samples (FileAccess app)

    void Scenario3::WriteLog(Platform::String^ str)
    {
     StorageFile^ file = rootPage->SampleFile;
     if (file != nullptr)
     {
      String^ userContent = str;
      if (userContent != nullptr && !userContent->IsEmpty())
      {
       create_task(FileIO::WriteTextAsync(file, userContent)).then([this, file, userContent](task<void> task)
       {
        try
        {
         task.get();
         rootPage->NotifyUser("The following text was written to '" + file->Name + "':\n" + userContent, NotifyType::StatusMessage);
        }
        catch (COMException^ ex)
        {
         rootPage->HandleIoException(ex, "Error writing to '" + file->Name + "'");
        }
       });
      }
      else
      {
       rootPage->NotifyUser("The text box is empty, please write something and then click 'Write' again.", NotifyType::ErrorMessage);
      }
     }
     else
     {
      rootPage->NotifyUserFileNotExist();
     }
    }

    void SDKTemplate::Scenario3::WriteTextButton_Click(Platform::Object ^sender, Windows::UI::Xaml::RoutedEventArgs ^e)
    {
     for (int i = 0; i < 10; i++)
      WriteLog(i.ToString());
    }

    Thanks.

    Tuesday, April 25, 2017 6:22 AM

All replies

  • Hello tgskumar,

    You may try think about some mutex action here. Mutex related API is still available in UWP like Rob mentioend here.

    At the same time I'm trying to involve someone here to help you on it.

    Best regards,

    Barry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, April 28, 2017 9:29 AM