I have a simple UWP app that I want to open a folder to access all the files in with. I'm using the stock example code from Microsoft for how to make a folder picker in UWP. However, after picking the folder (any folder) and trying to access it I always get this exception:
System.UnauthorizedAccessException
HResult=0x80070005
Message=Access to the path 'T:\temp' is denied.
Source=System.IO.FileSystem
StackTrace:
at System.IO.Enumeration.FileSystemEnumerator`1.CreateDirectoryHandle(String path, Boolean ignoreNotFound)
at System.IO.Enumeration.FileSystemEnumerator`1..ctor(String directory, EnumerationOptions options)
at System.IO.Enumeration.FileSystemEnumerable`1..ctor(String directory, FindTransform transform, EnumerationOptions options)
at System.IO.Enumeration.FileSystemEnumerableFactory.FileInfos(String directory, String expression, EnumerationOptions options)
at System.IO.DirectoryInfo.InternalEnumerateInfos(String path, String searchPattern, SearchTarget searchTarget, EnumerationOptions options)
at System.IO.DirectoryInfo.EnumerateFiles()
at ShutterShock.MainPage.<Button_Click>d__1.MoveNext() in C:\Users\nixca\source\repos\ShutterShock\ShutterShock\MainPage.xaml.cs:line 37
Mainpage.xaml.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace ShutterShock
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string path = await GetOpenLocation();
var boop = new DirectoryInfo(path);
boop.EnumerateFiles();
}
async Task<string> GetOpenLocation()
{
string returnText;
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
// Application now has read/write access to all contents in the picked folder
// (including other sub-folder contents)
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(folder);
returnText = folder.Path;
}
else
{
returnText = "Operation cancelled."; //todo make this an exception, catch that exception
}
return returnText;
}
}
}
I get the exception on the "boop.EnumerateFiles();" line.
So of course right after posting this it came to me, but I'll leave this up because I didn't actually find an answer anywhere before asking. The Microsoft example is dumb, and unless all you want is the path of the folder, returning the path is useless. The UWP filepicker doesn't actually grant you System.IO level access to the folder, all it gives you is a StorageFolder you can work on. If you want to do anything useful, you need to return the StorageFolder object, you can use that to actually work on files. This is probably obvious to people who actually know what they're doing.
If you wan to get all files in a selected folder, then you can use folder.GetFilesAsync().
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
var files = await folder.GetFilesAsync();
foreach(var file in files)
{
Debug.WriteLine(file.Path);
}
}
Here is the my result.
Related
Im having an issue with using DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open is not opening a spreadsheet, it returns a file not found exception. The class i'm using has worked many times before, but i've never used it in a UWP project.
I've created a simple example and found that I get the same issue when using File.Exists i've include all the using statements i use if that helps.
Does anyone know why the File.Exists cannot detect the file?
and yes i've triple checked the file does exist on D:!
C# UWP Project created using UWP Template Studio [MainPage.xaml.cs]
using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using UWP_APP.ViewModels;
using Windows.UI.Xaml.Controls;
namespace UWP_APP.Views
{
public sealed partial class MainPage : Page
{
public MainViewModel ViewModel { get; } = new MainViewModel();
public MainPage()
{
InitializeComponent();
string filePath = #"D:\example.xlsm";
if (File.Exists(filePath))
{
int a = 1;
}
else
{
int a = 0;
}
}
Does anyone know why the File.Exists cannot detect the file?
UWP app is running in sandbox, because File.Exists is System.IO api. So it could not work for accessing file except ApplicationData.Current.LocalFolder. If you do want to check if the file exist in the specific path, we suggest you add broadFileSystemAccess capability and enable in the system file access setting. This capability works for APIs in the Windows.Storage namespace.
And using the flolowing method to check if the file exist.
try
{
var file = StorageFile.GetFileFromPathAsync(#"C:\Users\Karan\OneDrive\Desktop\2010.pdf");
if (file != null)
{
isExist = true;
}
}
catch (Exception)
{
isExist = false;
}
I'm trying to use SharpCompress to read .rar files from my UWP application. It works fine on network shares from which I can read the archive no problem, but I get System.UnauthorizedAccessException on files anywhere on the local system including for instance USB drives. I have access to the files by other methods e.g. StorageFile. It makes no difference whether BroadFileSystemAccess is on or off. I've tried in both C# and Vb.net Here's the code of my test app in C#. The exception occurs at ArchiveFactory.Open.
I can also read Zip files no problem using the .net Compression methods but they can't do rar files, hence needing SharpCompress.
using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using SharpCompress;
using Windows.Storage.Pickers;
using Windows.Storage;
using SharpCompress.Archives;
namespace TestRAR
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
OpenRAR.Click += OpenRAR_Clicked;
}
public async void OpenRAR_Clicked(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".rar");
picker.FileTypeFilter.Add(".cbr");
picker.FileTypeFilter.Add(".cbz");
picker.FileTypeFilter.Add(".zip");
StorageFile pickfile = await picker.PickSingleFileAsync();
if (pickfile == null) { return; }
string pth = pickfile.Path;
FileInfo pickInfo = new FileInfo(pth);
try
{
ListRARs.Items.Clear();
using (var Arch = ArchiveFactory.Open(pickInfo))
{
foreach (IArchiveEntry a in Arch.Entries)
{
string thisKey = a.Key;
ListRARs.Items.Add(thisKey);
}
}
}
catch{ }
}
}
}
This is the first time I've used SharpCompress and I'm completely stumped. Any ideas anyone?
I'm developing a cross-platform application (UWP - Target version 16299, Android Target Version Pie and iOS; Visual Studio 2019 - Xamarin.Forms 4.1.0) which needs to communicate with a local DB file created inside AppData. All nice and fun until I try to export the information to another file, outside the AppData.
I've tried a bunch of things with no success and I'm curious why it works for you and not for me.
This is the latest code I've tested, similar to the others and with the same result:
Exception thrown: 'System.UnauthorizedAccessException' in System.Private.CoreLib.dll
using Plugin.FilePicker;
using Plugin.FilePicker.Abstractions;
using Plugin.Permissions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
namespace Testing
{
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private Plugin.FilePicker
.Abstractions.FileData file;
private async void ImportBtn_Clicked(object sender, EventArgs e)
{
try
{
file = await CrossFilePicker.Current.PickFile();
}
catch (Exception ex)
{
}
file.FileName = "rooms.jpg";
file.FilePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
await CrossFilePicker.Current.SaveFile(file);
}
private void ExportBtn_Clicked(object sender, EventArgs e)
{
{
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "download.txt";
string localPath = Path.Combine(documentsPath, localFilename);
try
{
File.Create(localPath);
}
catch(Exception ex)
{ Debug.WriteLine(ex); }
Debug.WriteLine(localPath);
}
}
}
}
I want to mention that all capabilities have been ticked, in a desperate attempt to get something to work, the import_clicked works as intended and the folders tried (Personal, Music, Pictures, Commons) are empty.
After testing ExportBtn_Clicked code in local proejct . It occurs the same error.
Exception thrown: 'System.UnauthorizedAccessException' in System.Private.CoreLib.dll
System.UnauthorizedAccessException: Access to the path 'C:\Users\xxx\Documents\download.txt' is denied.
at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.File.Create(String path)
at App8.MainPage..ctor()
This problem happens in UWP when accessing file from outside of app . Then I find a similar discussion about this error.
Access to the path 'C:\Sites\content\ServerIpAddress.txt' is denied
Then I refer to File access permissions ,the problem is UWP want to get files outside the scope of the app, you need to use Windows.Storage.If have a necessary to use Documents folder , you can refer to this to access it.
Accessing additional locations
using Windows.Storage;
var x = await StorageFolder.GetFolderFromPathAsync(#"C:\Users\UserName\Documents"); await x.CreateFileAsync("newfile.txt");
Note: Better using sandbox folder in application ,this will have the full permission .
In Android , if want to use External storage to realize it as follow:
Java.IO.File sdCard = Android.OS.Environment.ExternalStorageDirectory;
Java.IO.File dir = new Java.IO.File (sdCard.AbsolutePath + "/MyFolder");
dir.Mkdirs ();
Java.IO.File file = new Java.IO.File (dir,"download.txt");
if (!file.Exists ()) {
file.CreateNewFile ();
file.Mkdir ();
FileWriter writer = new FileWriter (file);
// Writes the content to the file
writer.Write (jsonData);
writer.Flush ();
writer.Close ();
}
I am writing code to copy an mp3 file into the local folder of an application. I am trying to use the CopyAsync method to do this, but a red squiggly line appears underneath this method and I'm unsure of how to fix it. The error specifies that there is no accessible extension method. It then advises if I'm missing an assembly reference or a user directive.
I've found extensive information on this method through Microsoft, so I know it's possible. I'm brand new to building apps in C#, so I am not quite sure how to fix it.
My code is included below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
namespace MusicLibraryTest
{
public static class LibraryHelper
{
public static async void ChooseMusic()
{
//Music Library is opened on user's computer and displays all available mp3 files
var picker = new Windows.Storage.Pickers.FileOpenPicker
{
ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.MusicLibrary
};
picker.FileTypeFilter.Add(".mp3");
//File is copied to local folder for use in music library
var file = picker.PickSingleFileAsync();
if (file != null)
{
await file.CopyAsync(ApplicationData.Current.LocalFolder);
}
}
Change this line:
var file = picker.PickSingleFileAsync();
To
var file = await picker.PickSingleFileAsync();
You're calling an async method that should be awaited.
Please, notice that this problem can only be reproduced with Visual Studio 2017 Preview. Otherwise, you won't be able to use iText7.
I'm posting this because it's very likely that the problem will remain when the final version comes out.
You can reproduce the issue following these steps:
Create a new Universal Windows project targeting Windows 10 Insider Preview (build
16278), also as the minimum version.
Add the package iText7, version 7.0.4-netstandard
Add one sample PDF file to the root of the project with Buid Action=Content and named "doc.pdf". It can be any PDF. I'm using this one: sample PDF.
Add this code to the MainPage.xaml.cs (code-behind)
MainPage.xaml.cs:
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Parser;
namespace App1
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
using (var stream = await GetStream("doc.pdf"))
{
var pdf = new PdfDocument(new PdfReader(stream));
var text = PdfTextExtractor.GetTextFromPage(pdf.GetPage(1));
}
}
private async Task<Stream> GetStream(string filename)
{
var uri = new Uri(new Uri("ms-appx:///"), filename);
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
return await file.OpenStreamForReadAsync();
}
}
}
Run the project
It will throw the NullReferenceException like this:
at iText.Kernel.Font.DocType1Font.CreateFontProgram(PdfDictionary
fontDictionary, FontEncoding fontEncoding, CMapToUnicode toUnicode)
at iText.Kernel.Font.PdfType1Font..ctor(PdfDictionary fontDictionary)
at iText.Kernel.Font.PdfFontFactory.CreateFont(PdfDictionary
fontDictionary) at
iText.Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor.GetFont(PdfDictionary
fontDict) at
iText.Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor.SetTextFontOperator.Invoke(PdfCanvasProcessor
processor, PdfLiteral operator, IList1 operands) at
iText.Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor.InvokeOperator(PdfLiteral
operator, IList1 operands) at
iText.Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor.ProcessContent(Byte[]
contentBytes, PdfResources resources) at
iText.Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor.ProcessPageContent(PdfPage
page) at
iText.Kernel.Pdf.Canvas.Parser.PdfTextExtractor.GetTextFromPage(PdfPage
page, ITextExtractionStrategy strategy, IDictionary`2
additionalContentOperators) at
iText.Kernel.Pdf.Canvas.Parser.PdfTextExtractor.GetTextFromPage(PdfPage
page) at App1.MainPage.d__1.MoveNext()