greg
greg

Reputation: 1204

Creating a new directory in a Windows 10 Universal App UWP

I am attempting to create a directory using this method that fires after a button press in app, as well as add a file to it:

DirectoryInfo d = new DirectoryInfo(@"..\\newFolder\\");
FileInfo f = new FileInfo(@"..\\newFolder\\foo.txt");
if (!d.Exists)
{
    d.Create();
}
if (!f.Exists)
{
    f.Create().Dispose();
}

Here's the error that is producded in my Universal App as a result of doing this:

An exception of type 'System.UnauthorizedAccessException' 
occurred in System.IO.FileSystem.dll but was not handled in user code

Additional information: Access to the path
 'C:\Users\[username]\Documents\MyApp\bin\x86\Debug\AppX\newFolder' is denied.

Any one familiar with this error or know of any suggestions?

EDIT In addition to the below, this is a Great resource for working with file systems in the Windows 10 Universal App environment: File access and permissions (Windows Runtime apps) https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh758325.aspx

Upvotes: 4

Views: 3181

Answers (4)

Ajaya Nayak
Ajaya Nayak

Reputation: 93

Try This

public static async void  WriteTrace()
{
  StorageFolder localFolder = ApplicationData.Current.LocalFolder;
  StorageFolder LogFolder = await localFolder.CreateFolderAsync("LogFiles", CreationCollisionOption.OpenIfExists);
 }

Upvotes: 1

Peter Torr
Peter Torr

Reputation: 12019

The problem is that you are trying to create a file inside your app's install folder, and that is not allowed for Universal Apps. You can only create folders inside your local data folder.

Try this:

using Windows.Storage;

var localRoot = ApplicationData.Current.LocalFolder.Path;
DirectoryInfo d = new DirectoryInfo(localRoot + "\\test");
if (!d.Exists)
  d.Create();

Upvotes: 4

MrRolling
MrRolling

Reputation: 2265

Every application runs under (by) a specific user and inherit it's privileges, authorities, limitations and ... so The User that your app runs under it, haven't enough privilege and can't create a folder SO you can:

  • Use Impersonation (search impersonation c#) and code your app to runs as another User with required privilege (Like Administrator). after that your application always runs as administrator (or specific user) automatically. (If you impersonation your app as Administrator, Be aware of Security issues)
  • Run your application as Administrator (or a user with enough privilege) manually. (for Administrator right click on your-app.exe and click on "Run as ...")
  • Change security settings and access limits for your working directories (e.g C:\Users[username]\Documents\MyApp\bin\x86\Debug\AppX\newFolder ) and give write access to your username

Upvotes: 0

Muneeb Zulfiqar
Muneeb Zulfiqar

Reputation: 1023

Run your application with Administrative privileges and it should be done.

Upvotes: 0

Related Questions