0

I am trying to write to a .txt file through my Windows 8.1 UA. My C# code looks like this:

var path = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile sampleFile = await path.GetFileAsync("info.txt");
await FileIO.WriteTextAsync(sampleFile, "new text");

And I am getting the System.UnauthorizedAccessException error when WriteTextAsync executes. I tried elevating my program and still same problem.

Checked all processes in case the .txt file is open somewhere, nothing.

File is not Read-only.

sampleFile.Path returns me a valid path C:\Users\myname\Documents\Visual Studio 2015\Projects\App2\App2\bin\Debug\AppX\info.txt

Any ideas what could be going wrong here? Sorry if this is a newbie question.

Edit: Adding error message Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll

Stacktrace

Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at App2.Data.SampleDataSource.<GetFreeSignal>d__11.MoveNext()

Adding GetFreeSignal function

public static async Task<string> GetFreeSignal()
        {

            string sURL = await GetLastPage();
            using (HttpClient clientduplicate = new HttpClient())
            {
                clientduplicate.DefaultRequestHeaders.Add("User-Agent",
                    "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");

                using (HttpResponseMessage responseduplicate = await clientduplicate.GetAsync(sURL))
                using (HttpContent contentduplicate = responseduplicate.Content)
                {
                    try
                    {
                        string resultduplicate = await contentduplicate.ReadAsStringAsync();

                        var websiteduplicate = new HtmlDocument();
                        websiteduplicate.LoadHtml(resultduplicate);
                        MatchCollection match = Regex.Matches(resultduplicate, "\\[B\\](.*?)<img", RegexOptions.Singleline);
                        var path = Windows.ApplicationModel.Package.Current.InstalledLocation;
                        StorageFile sampleFile = await path.GetFileAsync("info.txt");
                        await FileIO.WriteTextAsync(sampleFile, "new text");
                        return match[match.Count - 1].Groups[1].Value.TrimStart().Replace("&apos;", "'").Replace("&amp;", "&").Replace("&quot;", "\"").Replace("&rsquo;", "'").Replace("<br/>", "").Replace("<i>", "").Replace("</i>", "");
                    }
                    catch (Exception ex1)
                    {
                        Debug.WriteLine(ex1.StackTrace);
                        return string.Empty;
                        //throw ex1.InnerException;
                    }
                }
            }
        }
John P.
  • 1,199
  • 2
  • 10
  • 33
  • you have access to manually vs when you run it in the application then I would suggest you close VS and restart it as Admin and see if it works – MethodMan Feb 03 '17 at 20:05
  • @MethodMan already tried that. Didn't work – John P. Feb 03 '17 at 20:08
  • Maybe it's because the file is not created? You could try creating the file before executing the program. – AxelWass Feb 03 '17 at 20:15
  • @AxelWass It is created. As I already said, `.Path` returns me a valid path of the .txt file – John P. Feb 03 '17 at 20:19
  • Looking into [Microsoft documentation](https://msdn.microsoft.com/en-us/library/windows/apps/br227276.aspx) it says that this error is raised when you don´t have permissions over the folder. – AxelWass Feb 03 '17 at 20:20
  • 1
    I run into a similar issue with UWP development. You might not have access to that folder since UA/UWP is very sandboxed. Try using the User's AppData Storage folder and see if you have the same access problem. – Silas Reinagel Feb 03 '17 at 20:22
  • This might help: https://stackoverflow.com/questions/33082835/windows-10-universal-app-file-directory-access – Silas Reinagel Feb 03 '17 at 20:24
  • @SilasReinagel I just came to the same conclusion. I don't have access to that folder. Let me try and come back – John P. Feb 03 '17 at 20:25
  • @SilasReinagel nice shot buddy. Thank you. Add it as answer so I can accept it. – John P. Feb 03 '17 at 20:29

1 Answers1

2

This issue is caused by the sandboxing built into UA/UWP development. By default, applications are not allowed unrestricted access to the file system.

The easiest solution is to use the User's Local StorageFolder.

Here are other solutions: https://msdn.microsoft.com/en-us/windows/uwp/files/file-access-permissions

Silas Reinagel
  • 4,155
  • 1
  • 21
  • 28